Search code examples
phpconcatenationshortcode

How to use conditional statement in middle of concatenation


So I have three variables $blue_tooltip_icon, $red_tooltip_icon, and $gray_tooltip_icon. Now I would like a specific variable to be output depending on what attribute is passed onto a WordPress shortcode. So either $blue_tooltip_icon if 'blue' is entered, $red_tooltip_icon if 'red' is entered, and $gray_tooltip_icon if 'gray' is entered.

The problem is how to go about this. I tried using an if statement but found out that that's not possible in concatenation.

This is what I am trying to output via the shortcode with the tooltip icon being variable based on what color is entered through the shortcode attribute.

$message = '<span data-title="'.$atts['text'].'" class="tooltip">'.$content .$blue_tooltip_icon.'</span>'; 

Solution

  • I think this helps you.

    <?php
    // Cleaner way
    
    $blue_tooltip_icon = 'blue';
    $red_tooltip_icon = 'red';
    $green_tooltip_icon = 'green';
    
    $atts['text'] = 'john';
    $content = 'content';
    
    $icons = [
        'blue' => $blue_tooltip_icon,
        'red' => $red_tooltip_icon,
        'green' => $green_tooltip_icon
    ];
    
    $input = 'red';
    
    //$message = '<span data-title="' . $atts['text'] . '" class="tooltip">' . $content . $icons[$input] . '</span>';
    
    // Awkward style with ternary operator
    
    $input = 'green';
    
    $message = '<span data-title="' . $atts['text'] . '" class="tooltip">' . $content . (($input == "red") ? $red_tooltip_icon : (($input == "blue") ? $blue_tooltip_icon : $green_tooltip_icon)) . '</span>';
    
    echo $message;