Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65923155/change-css-color-of-text-based-on-php-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...