Support » Plugins and Hacks » Hacks » Show / Hide Tabs in PHP using Shortcode within IF Statement??

  • Resolved redwall

    (@redwall)


    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]');  ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • 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" ).

    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 );
    
    ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Show / Hide Tabs in PHP using Shortcode within IF Statement??’ is closed to new replies.