Support

Account

Home Forums General Issues Conditional logic to change output depending on which fields are active

Helping

Conditional logic to change output depending on which fields are active

  • I need to change the html markup depending on which of my ACF fields is active.
    I been testing around with this code but can’t wrap my head around the proper way to structure it.

    
    <?php
    if (get_field('link-1') And get_field('link-2') And get_field('link-3') ) {
    
    echo '<div class="red">';
        echo '<p>All 3 Links</p>';
    echo '</div>';
    }
    
    else if (get_field('link-1') And get_field('link-2') OR get_field('link-3') ) {
    
    echo '<div class="blue">';
        echo '<p>Link 1 and Link 2 OR Link 3</p>';
    echo '</div>';
    }
    
    else if (get_field('link-2') OR get_field('link-3') ) {
    
    echo '<div class="green">';
        echo '<p>Link 2 and Link 3 But not Link 1</p>';
    echo '</div>';
    }
            
    else if (get_field('link-1') OR get_field('link-2') OR get_field('link-3') ) {
    
    echo '<div class="hotpink">';
        echo '<p>One single Link</p>';
    echo '</div>';
    }
    ?>
    

    The third “else if” doesn’t work, it outputs the same result as the second “else if”, and if the link-3 option in the last “else if” statement is active it also outputs the same result as the second.
    But on a broader scale is this the most efficient way to go about these things? is there a more elegant way?

  • Below is the test code I was playing with. I used variables rather than ACF fields, but you can swap them back out.

    Also… I used || for OR, && for AND, and ! for “not equal to”

    Also… in the last conditional where you check for “One single link”… that won’t trigger when it’s just link 3, because the condition is already met when you output “Link 1 and Link 2 OR Link 3”.

    If you would like to tell me your purpose for the code, I may be able to offer a better solution.

    <?php
    $link1 = '1';
    $link2 = '';
    $link3 = '';
    if ( $link1 && $link2 && $link3 ) {
    
    echo '<div class="red">';
        echo '<p>All 3 Links</p>';
    echo '</div>';
    
    } else if ( ( $link1 && $link2 ) || ( $link3 && !$link1 && !$link2 ) ) {
    
    echo '<div class="blue">';
        echo '<p>Link 1 and Link 2 OR Link 3</p>';
    echo '</div>';
    
    } else if ( $link2 && $link3 && !$link1 ) {
    
    echo '<div class="green">';
        echo '<p>Link 2 and Link 3 But not Link 1</p>';
    echo '</div>';
    
    } else if ( ( $link3 && !$link1 && !$link2 ) || ( !$link3 && !$link1 && $link2 ) || ( !$link3 && $link1 && !$link2 ) ) {
    
    echo '<div class="hotpink">';
        echo '<p>One single Link</p>';
    echo '</div>';
    
    }
    ?>
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Conditional logic to change output depending on which fields are active’ is closed to new replies.