Ad

Change Background Color Based On Wordpress Post Metadata

I have created a frontend form that collects tennis match results using Wordpress and Advanced Custom fields. One of the form fields ('match_results') is a WIN or LOSS radio button.

Based on the value that is collected, I would like to update the background color of a column in the frontend display (created using Elementor).

In other words, if the custom field 'match_result' contains the value 'win', then the column should be green:

enter image description here

And if the custom field 'match_result' contains the value 'loss', then the column should be red:

enter image description here

I would like to solve this using a shortcode, as it makes it easier to work with in Elementor. I have created the following shortcode:

add_shortcode('match_result_sc', 'match_result_sc');

    function match_result_sc() { 
    global $post;
    
    $post_id = get_the_id ();
    $match_result = get_post_meta( $post_id, 'match_result' );

    $win =  '<div class="win_column" >';
    $win .= '</div>'; 
        
    $loss =  '<div class="loss_column" >';
    $loss .= '</div>'; 

    if($match_result = 'win')
        return $win;
    else
        return $loss;
    }

I have then placed the shortcode in the column in question and used the following custion CSS in an effort to change the background of the new div:

.win_column {
    background-color: red !important;
}

.loss_column {
    background-color: blue !important;
}

I've used a similar shortcode successfully using author metadata, but this doesn't seem to work. The new div doesn't seem to even appear, which leads me to think it's an error in my code. Any ideas where I've gone wrong? Any help would be greatly appreciated!

Ad

Answer

If your match_results field box is made with ACF, I think your assignment should be like:

$match_result = get_field('match_result', $post_id);

Then in your conditional you are missing an "=":

if($match_result == 'win')
  return $win;
else
  return $loss;
Ad
source: stackoverflow.com
Ad