且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-08-26 15:40:04

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

The following code will display the formatted linked product subcategories from current product category for product category archive pages:

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>';
}

经过测试,可以正常工作.

Tested and works.

用法示例:

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

1) You can use this code directly in archive-product.php template file.

2)您可以将代码嵌入函数中,替换最后一行 echo $ output.'</ul>'; 通过 return $ output.'</ul>'; ,对于简码,总是返回显示.

2) You can embed the code in a function, replacing the last line echo $output . '</ul>'; by return $output . '</ul>';, as for shortcodes, the display is always returned.

3)您可以使用动作钩子来嵌入代码,例如 woocommerce_archive_description :

3) You can embed the code using action hooks like 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文件中.经过测试,可以正常工作.

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

要在类别描述后显示它,请在以下位置将挂接优先级从 5 更改为 20 :

To display it after the category description, change the hook priority from 5 to 20 in:

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

喜欢:

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