You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 if statement (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_class variable first to avoid "undefined variable" warnings
  • Fixed the if/elseif logic 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:07:31