1

I have been able to show a list of Woocommerce category terms hierarchically. Now I'm struggling to get the first category term in the list as the default one. since I'm presenting the parent categories as tab links and the subcategories as tab contents. So how can get the first parent category that comes up as the default active tab?

I guess we could try to get something like:

<button class="tablinks <?php if ( $first_element == $default_active_tab ) echo esc_attr( 'active' ); ?>"

This is the code to get all parent product category terms,

<?php
    $parent_args = array(
        'taxonomy' => 'product_cat',
        'hide_empty' => true,
        'parent'   => 0
    );

    $product_cat = get_terms( $parent_args );

    foreach ($product_cat as $parent_cat)
    {
        echo'<buttonclass="tablinks"onclick="myFunction(event,\''.$parent_cat->name.'\')">'.$parent_cat->name.'</button>';
    }
?>

1 Answer 1

1

Try the following improved code, to get "active" on the first item:

<?php
    $product_cats = get_terms([
        'taxonomy'   => 'product_cat', 
        'hide_empty' => true, 
        'parent'     => 0, 
        'fields'     => 'names' // Term names
    ]);

    foreach ( $product_cats as $key => $parent_term_name ) {
        printf( '<button class="tablinks %s" onclick="%s">%s</button>',
            $key === 0 ? esc_attr( 'active' ) : '',
            "myFunction(event,'{$parent_term_name}')",
            $parent_term_name
        );
    }
?>
1
  • You just saved my day, works awesomely as expected, thanks! Just '{$parent_term_name}'
    – Mitos
    Commented May 5, 2019 at 3:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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