0

Im trying to add new feature to the theme and that's show/hide page title,but since i already have about 50 posts i can't go to all of them and save again just to save custom field values.

So i tried to make check if custom field doesn't exist, or if exist but not set to false show the title. But im failing at some point.

Custom field is metabox with checkbox, when checked it records "1" in database, when unchecked records "0" in database. And of course since im adding it now, 50 posts doesn't have that field in database.

Here is my last tryout.

if ( empty(vf_get_meta($post->ID, 'page_options', 'show_title')) || (vf_get_meta($post->ID, 'page_options', 'show_title') == true ))

This should check if meta is empty or if it's true and show page title. But something im not understanding. Isn't return false if it's empty?

How do i do it than?

  • What is vf_get_meta()? What does it return? – s_ha_dum Feb 1 '14 at 4:49
  • vf_get_meta is almost the same as get_post_meta only returns one more field, if meta is saved in an array. Anyway answer below solved my problem. – Aleksandar Đorđević Feb 1 '14 at 5:33
0

empty checks for several things:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)

In short, you are running a check if the value evaluates to false or does the value evaluate to true. Either way it will always evaluate to true.

Now I don't know what the function vf_get_meta returns for empty values. If you look at core get_post_meta function, it returns either an empty array or an empty string when the single flag is set to true.

I think the best rewrite will be this:

if ( vf_get_meta($post->ID, 'page_options', 'show_title') !== false )

We are saying, as long as it is not set to false, do it. You'll notice that I used !== instead of !=. The !== is the "Not Identical" comparison instead of the != "Not Equal". PHP will convert certain values into a boolean true or false for the equality comparison. Sometimes you'll hear people say a value is "truthy" or "falsey" reflecting how it will be convert to a boolean value.

  • Sorry i didn't clarified what is vf_get_meta, it's just a function similar to get_post_meta it only returns second array if meta is saved in an array like show_title. Anyway you understood what was the problem and !== solved it. Thanks. – Aleksandar Đorđević Feb 1 '14 at 5:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.