I am currently trying to create a shortcode for WordPress that creates tabs, I know there are available shortcodes.. But I am trying to learn how to write them myself.
Currently I am generating the tab menu items, but i am stuck with placing the content in an entirely new div.
Front end Usage:
[tabs]
[tab title="tab" active="y" id="home"]home[/tab]
[tab title="tab2" active="n" id="about"]about[/tab]
[tab title="tab3" active="n" id="help"]help[/tab]
[/tabs]
And then the code:
function tabs_group( $atts, $content = null ) {
extract(shortcode_atts(array(
'id' => '',
'class' => ''
), $atts));
$output = '<ul class="nav nav-tabs '.$class.'" ';
if(!empty($id))
$output .= 'id="'.$id.'"';
$output .='>'.do_shortcode($content).'</ul>';
return $output;
}
add_shortcode("tabs", "tabs_group");
function tab($atts, $content = null) {
extract(shortcode_atts(array(
'id' => '',
'title' => '',
'active'=>'n'
), $atts));
if(empty($id))
$id = 'tab_item_'.rand(100,999);
$output = '<li class="'.($active == 'y' ? 'active' :'').'">
<a href="#'.$id.'">'.$title.'</a>
</li>';
$output .= '<div class="tab-content">
<div class="tab-pane active" id="'.$id.'">'.$content.'</div>
<div class="tab-pane" id="'.$id.'">'.$content.'</div>
<div class="tab-pane" id="'.$id.'">'.$content.'</div>
</div>';
return $output;
}
add_shortcode("tab", "tab");
it currently returns:
<ul class="nav nav-tabs">
<li class="active">
<a href="#home">tab</a>
</li><div class="tab-content">
<div class="tab-pane active" id="home">home</div>
<div class="tab-pane" id="home">home</div>
<div class="tab-pane" id="home">home</div>
</div>
<li class="">
<a href="#about">tab2</a>
</li><div class="tab-content">
<div class="tab-pane active" id="about">about</div>
<div class="tab-pane" id="about">about</div>
<div class="tab-pane" id="about">about</div>
</div>
<li class="">
<a href="#help">tab3</a>
</li><div class="tab-content">
<div class="tab-pane active" id="help">help</div>
<div class="tab-pane" id="help">help</div>
<div class="tab-pane" id="help">help</div>
</div>
</ul>
and i need it to return:
<ul class="nav nav-tabs " >
<li class="active">
<a href="#home">tab</a>
</li>
<li class="">
<a href="#about">tab2</a>
</li>
<li class="">
<a href="#help">tab3</a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">blah</div>
<div class="tab-pane" id="about">blah</div>
<div class="tab-pane" id="help">blah</div>
</div>
I have added to the output, thank you Obmerk Kronen.
Any Help Greatly Appreciated.
The problem here is that you need to add your divs after
do_shortcode($content)
: while parsingtab
shorcodes, you need to keep your divs somewhere to be able to output them after.A simple way (not nicest way) for doing this could be using a global var, e.g. :
you do not currently have the content part of the divs in your content
wordpressshortcode