WordPress餐厅点评页面:根据1-100评分动态调整评分模块背景色的技术实现问题
Dynamic Background Color for Restaurant Ratings in WordPress
Hey there! Let's get your dynamic rating background colors working properly. I spotted a couple of small issues in your attempted code that caused the error, and we'll fix them step by step.
First: Fix the PHP Code
Your original code had two main problems:
- Incorrect syntax for the
ifstatement (extra semicolon after the curly brace, plus missing proper range checks for all score tiers) - Using
+for string concatenation (PHP uses.for this instead)
Here's the corrected PHP code that will assign the right class based on the score:
<?php if ( class_exists( "Lets_Review_API" ) ) { $lr_api = new Lets_Review_API(); $final_score_value = $lr_api->lets_review_get_final_score_only( $post_id ); // Initialize the score class variable to avoid undefined errors $score_class = ''; // Assign class based on your desired score ranges if ($final_score_value >= 1 && $final_score_value <= 40) { $score_class = 'score-red'; } elseif ($final_score_value >= 41 && $final_score_value <= 80) { $score_class = 'score-yellow'; } elseif ($final_score_value >= 81 && $final_score_value <= 100) { $score_class = 'score-green'; } // Correctly add the class to the div (using PHP's . for concatenation) echo '<div class="show-score ' . $score_class . '"><h4>' . $final_score_value . '%</h4></div>'; } ?>
Second: Add CSS for the Color Classes
Now add these CSS rules to your theme's stylesheet (or the Custom CSS section in WordPress) to set the background colors for each score range:
/* Red background for low scores (1-40) */ .show-score.score-red { background-color: #dc3545; /* Use this hex code or replace with your preferred red */ } /* Yellow background for medium scores (41-80) */ .show-score.score-yellow { background-color: #ffc107; /* Adjust this hex code to match your site's yellow */ } /* Green background for high scores (81-100) */ .show-score.score-green { background-color: #28a745; /* Swap this with your desired green if needed */ }
Quick Breakdown of the Fixes:
- We initialized the
$score_classvariable first to avoid "undefined variable" warnings - Fixed the
if/elseiflogic to cover all score ranges correctly (including boundary values like 40 and 80) - Used PHP's correct string concatenation operator (
.) instead of+ - Added specific color classes that override the default background color from your original CSS
This should work smoothly now—when a restaurant has a score between 1-40, the box will be red, 41-80 will be yellow, and 81-100 will be green.
内容的提问来源于stack exchange,提问作者Haris
相关产品推荐
相关产品推荐

