Lee
Lee

Reputation: 4323

Why is this get_post_meta returning the wrong value?

Trying to show a display notice based on the previous page, using it's post ID.

The problem is that the post meta value is stored in Wordpress as 0 (zero), but my statement is returning it as being true, when it should be false.

$previous_page = url_to_postid(wp_get_referer());
$consultationFee = null;
if(get_post_meta($previous_page, '_wp_page_template', true) == 'template-procedure-minimal.php') {
    if(get_post_meta($previous_page, 'consultationFee', true) && get_post_meta($previous_page, 'consultationFee', true) === 0) {
        $consultationFee = false;
    } else {
        $consultationFee = true;
    }
}
var_dump($previous_page, get_post_meta($previous_page, 'consultationFee', true), $consultationFee);

C:\wamp64\www\bellavou\wp-content\themes\bellavou\template-request-consultation.php:11:int 3209
C:\wamp64\www\bellavou\wp-content\themes\bellavou\template-request-consultation.php:11:string '0' (length=1)
C:\wamp64\www\bellavou\wp-content\themes\bellavou\template-request-consultation.php:11:boolean true

I notice the var_dump of the value is being returned as a string. IS this right? This should be an integer. Anyway, even changing the IF statement to check against a string ie. === '0' returns the wrong value still.

What's happening?

Upvotes: 0

Views: 1758

Answers (1)

Samvel Aleqsanyan
Samvel Aleqsanyan

Reputation: 2960

Your code working right ( as written ).

  1. First block:

    if(get_post_meta($previous_page, 'consultationFee', true)){
    
    }else{
      //will always work this code, because '0' converted to 0( false )
    }
    
  2. Second block:

    if(get_post_meta($previous_page, 'consultationFee', true) === 0){
    
    }else{
      //will always work this code, because ( string )'0' not equeal to ( int )0
    }
    

    get_post_meta() will return string, if last parameter $single set as true. And will return empty string ( '' ), if no value will found. So, we can't check it with isset() and empty() function. isset(get_post_meta($previous_page, 'consultationFee', true)) will always be true, and as you're expecting the return value be ( string )'0' empty(get_post_meta($previous_page, 'consultationFee', true)) will always be true.

Your $consultationFee will always be true, because:

if(get_post_meta($previous_page, 'consultationFee', true)/*returns false*/ && get_post_meta($previous_page, 'consultationFee', true) === 0/*returns false*/) {
    $consultationFee = false;
} else {
    //we will reach this block
    $consultationFee = true;
}

if you want to compare returned value of get_post_meta with ( string )'0', use this:

if(get_post_meta($previous_page, 'consultationFee', true) === '0'))

Upvotes: 2

Related Questions