最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Make the first item as default on Woocommerce product category items list

programmeradmin2浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 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
        );
    }
?>
发布评论

评论列表(0)

  1. 暂无评论