0

I have a page that displays products based on a previous user query. The search results contain sets of metadata, most importantly a "product rating" on a 1-10 scale.

Here's the code that pulls the product rating metadata

<?php echo get_post_meta( get_the_ID(), 'product_rating', true ); ?>

This pulls the 'rating' metadata from our dB and simply displays the rating as a numeral (1, 1.5, 2, 2.5 ect).

I'm looking to take the value of the 'product_rating' and set an image to display for each value. A rating of 1 will display one image, while a rating of 2 display a different image ect ect.

The current code I have in place substitutes an image for the value, but the image is displaying multiple times (up to 10 times for a single value). My code is below, using a rating value of "4" as an example.

<?php $rating = get_post_meta( get_the_ID(), 'product_rating', true ); ?>

<?php For($i=4; $i <= $rating; $i++){
echo "<img src='http://www.domain.com/lpimage/lock50.png' />";
}
?>

Is my code close to where I need to be, or am I completely off base for the function I want?

3
  • Are your ratings real numbers, i.e. you could have a 1.234, or are they guaranteed to be in steps of 0.5? Commented Jul 26, 2014 at 1:54
  • And also, how many images do you expect to use, and what is the maximum rating? Is the minimum zero, or can it become negative? Commented Jul 26, 2014 at 1:59
  • Ratings are in steps of .5, with 0 being the lowest. I'm going to use around 20 images, which will simply be stars that are correspondingly filled to match the product rating. A rating of 4 will have 4 gold stars, with 6 empty stars. Commented Jul 26, 2014 at 2:14

1 Answer 1

1

Assuming your rating variable is correctly defined I think you can handle the conditional display of various images as follows:

<?php if ($rating == 1) echo '<img src="urlofimage1.jpg"></img>';
  elseif ($rating == 2) echo '<img src="urlofimage2.jpg"></img>';
  elseif ($rating == 3) echo '<img src="urlofimage3.jpg"></img>';
  elseif ($rating == 4) echo '<img src="urlofimage4.jpg"></img>';
?>

You use the double equal sign when comparing a value, you only use the single equal sign (=) when setting a variable's value.

Use >= and <= for ranges, ie. 1.3 or 2.7

Sign up to request clarification or add additional context in comments.

1 Comment

Absolutely perfect, I really appreciate the time and extra info!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.