Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've created a recursive shortcode that looks like this.

[tabs]
[tab state="active"]Home[/tab]
[tab]About[/tab]
[tab]Contact[/tab]
[/tabs]

[tabcontent]
[tabpane]Content 1[/tabpane]
[tabpane]Content 2[/tabpane]
[tabpane]Content 3[/tabpane]
[/tabcontent]

It is working, but I would like to remove the state="active" and automatically add that to the first tab, but I'm not sure how to tell which iteration my do_shortcode is on?

Update: What would be even better is if I could keep a count while iterating through the do_shortcode so I could add attributes like id="tab1", id="tab2".

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

Figured out both issues. You can keep a count and find out when you are on the first iteration in the same go.

static $count;
if(!$count) {
    $count = 1;
    $state = ' active';
} else {
    $count++;
    $state = '';
}

From the PHP Manual. "A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope."

This code sets a static variable within the recursive function, in this case a function called by do_shortcode(). This lets you keep a count going so if you wanted to have id's like #tab-1, #tab-2 you could easily do so. With this code you can also tell when the first iteration happens. I set a $state variable and give it an active css class. Since I'm appending it to a class attribute already I've only got active, but you could also pass the whole thing if you only had one class like class="active" for example.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.