phpwordpresspost-meta

What's the best way to store post_meta value in variable, with a default value?


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)


Solution

  • 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;