1

What's the most efficient and simplest way to store a post_meta value in a variable, along with a default value if the meta_key doesn't exist?

I want to use something like this, the meta_value will always be a number:

$bv_faq_thumbs_up = isset(get_post_meta($post->ID, '_bv_faq_thumbs_up', true)) ? get_post_meta($post->ID, '_bv_faq_thumbs_up', true) : 0;

But this throws a PHP error:

Fatal error: Cannot use isset() on the result of an expression

Off the top of my head, the only thing I can think of something like:

if(get_post_meta($post->ID, '_bv_faq_thumbs_up', true) === null) {
    $bv_faq_thumbs_up = 0;
} else {
    $bv_faq_thumbs_up = get_post_meta($post->ID, '_bv_faq_thumbs_up', true);
}

But that seems quite long-winded and bloated, is this the correct way (in terms of speed and efficiency, and tidiness)

Lee
  • 4,187
  • 6
  • 25
  • 71

3 Answers3

1

Try this code;

$bv_faq_thumbs_up = get_post_meta($post->ID, '_bv_faq_thumbs_up', true);

if(empty($bv_faq_thumbs_up)) {
    $bv_faq_thumbs_up = 0;
}

OR

$bv_faq_thumbs_up = get_post_meta($post->ID, '_bv_faq_thumbs_up', true);

$bv_faq_thumbs_up = (!empty($bv_faq_thumbs_up)) ? $bv_faq_thumbs_up : 0;

OR

if(metadata_exists( 'post', $post->ID, '_bv_faq_thumbs_up' ) === null) {
    $bv_faq_thumbs_up = 0;
} else {
    $bv_faq_thumbs_up = get_post_meta($post->ID, '_bv_faq_thumbs_up', true);
}

for future users

Vel
  • 9,027
  • 6
  • 34
  • 66
  • Thanks very much for your answer, however I like the idea that Stender gave in the comments if that's alright. – Lee Feb 16 '18 at 10:07
1

Based on Stender's comment, I found using metadata_exists instead of isset allows the same idea to work, still contained within a single sentence, and only using the get_post_meta() function once, whilst setting a default value.

$bv_faq_thumbs_up = metadata_exists('post', $post->ID, '_bv_faq_thumbs_up') ? get_post_meta($post->ID, '_bv_faq_thumbs_up', true) : 0;
Lee
  • 4,187
  • 6
  • 25
  • 71
0

You can do this since PHP 7:

$result = get_post_meta($id, $key, true) ?? false; // false is default value

Alternative:

if (($result = get_post_meta($id, $key, true) ?? false) !== false) {
    // do stuff but only if the $key exists
    echo $result;
}

There is no need to call metadata_exists() or get_post_meta() twice. Explanation for ?? can be found here https://www.phptutorial.net/php-tutorial/php-null-coalescing-operator/

Nexarius
  • 346
  • 4
  • 11