I’m trying to do a simple if function on my code but for some reason it just isn’t working correctly. I’ve gone over it several times to see if there is anything I’m missing, but no luck. I’m trying to say my value is 0 then echo nothing if not else the_ratings. Very simple…
<?php if( get_post_meta( $post_id, 'ratings_users', true ) === '0' ) {
}else{
the_ratings();
} ?>
<?php if(!get_post_meta( $post_id, 'ratings_users', true ) !='0' ) {
}else{
the_ratings();
} ?>
<?php if(get_post_meta( $post_id, 'ratings_users', true ) =='0' ) {
}else{
the_ratings();
} ?>
Edit: at this point I’ve tried 3 different ways to get this stupid thing to output nothing if the value in the custom field is 0 and still it doesn’t work correctly.
6 Answers
The reason you have a problem is 0
is also considered equal to false, when the get_post_meta
call returns false, it’s also the same as being equal to 0
.
if( !get_post_meta( $post_id, 'some-non-existant-field', true ) == 0 )
Would be the same as …
if( get_post_meta( $post_id, 'some-existing-field', true ) == 0 )
..the only difference is in one case the field doesn’t exist, and in one it does(and has a zero value), both will be true though.
Additionally, 0
is not the same as '0'
, ie. one is a string value, the other an actual numeric value. Custom field values are stored as strings, so your comparison should go along the lines of..
if( get_post_meta( $post_id, 'some-existing-field', true ) == '0' )
.. to be accurate.
I realise i’m bad at explaining this, so i hope that helps(or someone else explains it better).