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>';
}
?>
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>';
}
?>
Share
Improve this question
edited May 4, 2019 at 6:16
LoicTheAztec
3,39117 silver badges24 bronze badges
asked May 3, 2019 at 18:36
MitosMitos
557 bronze badges
1 Answer
Reset to default 1Try 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
);
}
?>