0

I'm using the WP-Ratings plugin which uses the Wordpress built in custom fields to save values of ratings. The name of the custom field is ratings_score. I want to ask if each post has a specific rating. What I'm doing is inside the loop doing following:

<?php $rating = get_post_meta($post->ID, 'ratings_score', false); ?> 

<?php if ( $rating == 2 ) ) { ?>
    <script>
        console.log("test");
    </script>
<?php } ?>

But it does not work. Am I doing it wrong? I also tried to ask if ( $rating == '2' ) but thats the same issue. There are definately posts which have 2 as value of ratings_score

1 Answer 1

2

Try:

$rating = get_post_meta($post->ID, 'ratings_score', false); 
var_dump($rating);

You will notice that you get an array, even if your ratings_score is 2. To wit:

array(1) {
  [0]=>
  string(1) "2"
}

That will never equal 2 so your condition will never work.

The third parameter of get_post_meta() if set to true will collapse that array to a scalar, and that will work.

$rating = get_post_meta($post->ID, 'ratings_score', true); 
var_dump($rating);

Note that if your post has multiple ratings_scores you will only get one of them and it may not be the one you want.

To make this work with multiple ratings_score entries use:

$rating = get_post_meta($post->ID, 'ratings_score', false); 

if (in_array(2,$rating)) {
  echo 'found it';
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.