I have the below div where i use a PHP if else to change the background color of the div based on the $tteg value which is equal to a JS value called {{ reviewsOverall }} , i don’t know if i did equal them correctly but it seems to work, the problem i am facing is the color of the background is always red, i am not sure if the below code is correct, please help.
What i want to do is IF {{ reviewsOverall }} value is below 7 div background-color to be red, else to be green, i want to mention that {{ reviewsOverall }} value starts from 0 till 10 and when its for example 5 its without decimals but if its 3.1 or others its with one decimal after the point. I am adding the below code in WordPress Plugin editor, thanks in advance for your help, much appreciated.
<div
class="rwp-users-score <?php if ( $is_UR ) echo 'rwp-ur' ?>"
<?php $tteg = "{{ reviewsOverall }}"; ?>
<?php if ($tteg < 7): ?>
style='background-color: red;'
<?php elseif ($tteg >= 7): ?>
style='background-color: green;'
<?php else: ?>
style='background-color: black;'
<?php endif ?> >
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
PHP can’t read JavaScript variables – that’s because they are simply not available at the point that PHP is run.
So, in this case, you are better staying with pure JavaScript to accomplish what is really a UI challenge – it will also make your code cleaner and better organised.
Here is a basic ( untested ) solution:
<script>
$( function() {
color = 'red'; // default ##
if ( '7' >= reviewsOverall ){
color = 'blue';
} elseif ( '7' < reviewsOverall ){
color = 'pink';
}
$('.rwp-users-score').css('background-color', color );
});
</script>
This script could be added inline on the template or added to a scripts.js file and included using wp_enqueue_script() – https://developer.wordpress.org/reference/functions/wp_enqueue_script/
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0