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.
The reason you have a problem is
0
is also considered equal to false, when theget_post_meta
call returns false, it’s also the same as being equal to0
.Would be the same as …
..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.... to be accurate.
I realise i’m bad at explaining this, so i hope that helps(or someone else explains it better).
To extand Marc Duncans (a.k.a. @t31os) answer:
You multiple ways to question “
if ( $some_val_A IS $some_val_B )
“. There is a difference between equal and identical.As you can see (when you paste
wpse26016_test_vars()
in your template), there’s a difference between comparing “against value” or type “against value and type”.Use this function always to see if you’re doing it right 🙂
Based on your clarification, I would recommend something like the following:
Alternately, you could use:
But I think the first method will work; and is more concise.
The important thing to note here is that
get_post_meta()
returns an empty string if the post meta value isn’t set.I appreciate all the answers but $post_id was the issue it should have been $post->ID
Try this:
false
if the key doesn’t existsIf you’re using wp-postratings or any other plugin that uses custom_fields, they don’t create the key until it is used, so you can save time doing: