简体   繁体   中英

Change CSS color of text based on PHP variable

I have been searching for days now and I have tried countless times but all the examples I have tried are not working. I have a field that pulls a variable and I want to change the color of the text based on the selection of that variable. So if the variable is set to Undecided I want the text to change to red but if any other option is selected I want it to remain black. This is the line of code on the template for the page that pulls the variable which is currently working correctly:

<p id="orient" style="color:#<?php echo $style; ?> "><strong>Orientation: <?php echo get_field('orientation',get_the_ID()); ?></strong></p>

I then tried a bunch of ways but this is what I am currently trying to get to work:

var ori = "<?php echo get_field('orientation',get_the_ID()); ?>";

if ($ori == "Undecided") {
  $style="FFF";
};

I keep getting an error saying the variable is undefined but I do not understand why? What am I doing wrong here? How do I set the variable correctly? Or is there a better way to do this?

I was able to get it to work by updating the code to look like this:

<?php 
    $ori = get_field('orientation',get_the_ID());
                                            
    if ($ori == "Undecided") {
    $style="FFF";
};
?>

The problem was the <?php echo portion in the variable because I copied it from another field and I was already writing in PHP so I had to remove that section and it worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM