为了账号安全,请及时绑定邮箱和手机立即绑定

获取 Woocommerce 档案中当前产品类别的子类别

获取 Woocommerce 档案中当前产品类别的子类别

PHP
狐的传说 2021-12-24 10:18:23
我正在尝试在 Woocommerce 中显示当前类别下的子类别(不是子类别等),比如这个网站:http ://www.qs-adhesivos.es/app/productos/productos.asp?idioma=en例如,建筑是类别,密封剂和粘合剂、防水材料、聚氨酯泡沫……是子类别。密封剂和胶粘剂是类别,而醋酸硅酮密封剂、中性硅酮密封剂、丙烯酸密封剂……是子类别……在我的子主题下的 woocommerce 文件夹中已经有一个 archive-product.php。已经尝试了一些代码并且它适用,但这不是我想要的。
查看完整描述

1 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

以下代码将显示产品类别存档页面的当前产品类别的格式化链接产品子类别:


if ( is_product_category() ) {


    $term_id  = get_queried_object_id();

    $taxonomy = 'product_cat';


    // Get subcategories of the current category

    $terms    = get_terms([

        'taxonomy'    => $taxonomy,

        'hide_empty'  => true,

        'parent'      => get_queried_object_id()

    ]);


    $output = '<ul class="subcategories-list">';


    // Loop through product subcategories WP_Term Objects

    foreach ( $terms as $term ) {

        $term_link = get_term_link( $term, $taxonomy );


        $output .= '<li class="'. $term->slug .'"><a href="'. $term_link .'">'. $term->name .'</a></li>';

    }


    echo $output . '</ul>';

}

测试和工作。


使用示例:


1) 您可以直接在archive-product.php模板文件中使用此代码。


2)可以在一个功能嵌入的代码,替换最后一行echo $output . '</ul>';通过return $output . '</ul>';,对于简码,总是返回显示。


3)您可以使用以下动作挂钩嵌入代码woocommerce_archive_description:


// Displaying the subcategories after category title

add_action('woocommerce_archive_description', 'display_subcategories_list', 5 ); 

function display_subcategories_list() {

    if ( is_product_category() ) {


        $term_id  = get_queried_object_id();

        $taxonomy = 'product_cat';


        // Get subcategories of the current category

        $terms    = get_terms([

            'taxonomy'    => $taxonomy,

            'hide_empty'  => true,

            'parent'      => $term_id

        ]);


        echo '<ul class="subcategories-list">';


        // Loop through product subcategories WP_Term Objects

        foreach ( $terms as $term ) {

            $term_link = get_term_link( $term, $taxonomy );


            echo '<li class="'. $term->slug .'"><a href="'. $term_link .'">'. $term->name .'</a></li>';

        }


        echo '</ul>';

    }

}

代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。


要将其显示在类别描述之后,请将挂钩优先级从更改5为20in:


add_action('woocommerce_archive_description', 'display_subcategories_list', 5 ); 

喜欢:


add_action('woocommerce_archive_description', 'display_subcategories_list', 20 ); 


查看完整回答
反对 回复 2021-12-24
  • 1 回答
  • 0 关注
  • 176 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号