WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Show / Hide Tabs in PHP using Shortcode within IF Statement?? (3 posts)

  1. redwall
    Member
    Posted 1 year ago #

    I have inserted a set of tabs to my php wordpress template using the following shortcodes

    <?php echo do_shortcode('[tabs style="boxed"]
                [tab title="1"][some content here][/tab]
                [tab title="2"]' . get_the_excerpt() . '[/tab]
                [/tabs]');  ?>

    This works fine.

    I have created 2 x custom checkbox fields called 'tab_contact_1' and 'tab_contact_2' in a custom post.

    I would like to add conditional logic to the tabs so that if the checkbox is true/checked the tab shows. If not it hides. (This is due to some posts having this content available and some not)

    I have similar logic working for other custom fields on the site, but not using tabs and was thinking I can apply the same mindset. I took a go at the code (see below) but the page is not loading. I am doing something wrong but can't figure it out. Was hoping for some guidance.

    thanks a lot

    <?php echo do_shortcode('[tabs style="boxed"]
    ' . if ( get_post_meta($post->ID, 'tab_contact_1', true)) { . '
    [tab title="1"][some content here][/tab]
    '. } .'
    ' . if ( get_post_meta($post->ID, 'tab_contact_2', true)) { . '
    [tab title="2"]' . get_the_excerpt() . '[/tab]
    '. } .'
    [/tabs]');  ?>
  2. s_ha_dum
    Member
    Posted 1 year ago #

    if's won't work embedded in a string like that. You should be getting a fatal error. You can use a ternary operator though.

    do_shortcode('[tabs style="boxed"]'.
    ((!empty(get_post_meta($post->ID, 'tab_contact_1', true))) ? get_post_meta($post->ID, 'tab_contact_1', true) : '').'[/tabs]');

    The ternary operator is ( (statement to evaluate) ? "do if true" : "do if false" ).

  3. redwall
    Member
    Posted 1 year ago #

    Hi Thanks but I got this answer from stackoverflow which works nicely

    <?php
    
    $result = '';
    
    $result .= '[tabs style="boxed"]';
    if ( get_post_meta( $post->ID, 'tab_contact_1', true ) != 'false' ) {
        $result .= '[tab title="1"][some content here][/tab]';
    }
    if ( get_post_meta( $post->ID, 'tab_contact_2', true ) != 'false' ) {
        $result .= '[tab title="2"]' . get_the_excerpt() . '[/tab]';
    }
    $result .= '[/tabs]';
    
    echo do_shortcode( $result );
    
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic