在存档上显示子类别描述 - Woocommerce

问题描述 投票:0回答:1

我使用此代码来显示类别描述:

  <?php 
 global $post;
$args = array( 'taxonomy' => 'product_cat');
$terms = get_the_terms($category->slug,'product_cat', $args);

    $count = count($terms); 
    if ($count > 0) {

        foreach ($terms as $term) {
            echo '<div class="prod-descr" style="direction:ltl;">';
            echo $term->description;
            echo '</div>';

        }

    }

?>  

它可以工作,但会在子类别上显示父类别描述。我需要在子类别上隐藏父类别描述,并仅显示子类别描述。

有什么帮助吗?

感谢您的帮助

php wordpress woocommerce hook-woocommerce
1个回答
0
投票

以下代码应该可以工作。

我不确定你在这里做什么:

$terms = get_the_terms($category->slug,'product_cat', $args);

因为我相信

get_the_terms
需要一个
ID
。 所以在我的示例中,它是一个 ID(将
'1'
更改为
get_the_ID()
或尝试其他方法来获取 ID。

但也许你的

$category->slug
也有效。或者
$category->term_id
。你需要尝试一下。

<?php
//Get all terms associated with post in taxonomy 'category'
$terms = get_the_terms('1','product_cat');

//Get an array of their IDs
$term_ids = wp_list_pluck($terms,'term_id');

//Get array of parents - 0 is not a parent
$parents = array_filter(wp_list_pluck($terms,'parent'));

//Get array of IDs of terms which are not parents.
$term_ids_not_parents = array_diff($term_ids,  $parents);

//Get corresponding term objects
$terms_not_parents = array_intersect_key($terms,  $term_ids_not_parents);


global $post;
$args = array( 'taxonomy' => 'product_cat');

    $count = count($terms_not_parents);
    if ($count > 0) {

        foreach ($terms_not_parents as $term) {
            echo '<div class="prod-descr" style="direction:ltl;">';
            echo $term->description;
            echo '</div>';

        }

    }

?>

基于此答案

© www.soinside.com 2019 - 2024. All rights reserved.