woocommerce - 如何获得当前产品类别中最顶级的类别

Gma*_*man 11 php wordpress woocommerce

我有一个Woocommerce产品,我需要在该页面上显示分配给该产品的类别的最顶级类别

- Main Product Category
-- Sub Product Category
--- Category Assigned to product
Run Code Online (Sandbox Code Playgroud)

我需要获取"主要产品类别"的ID或名称,以便我可以在单个产品类别中显示它.

我已经尝试过以下操作:

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );

foreach ($terms as $term) {
$product_cat_id = $term->term_id;

$thetop_parent = woocommerce_get_term_top_most_parent( $product_cat_id , 'product_cat' );

echo $thetop_parent;
}
Run Code Online (Sandbox Code Playgroud)

但它根本没用,它在woocomerce_get_term之后加载页面......我不知道该怎么办呢

感谢您的帮助.

Gma*_*man 25

经过大量的研究,我想出了解决这个问题的方法.我希望这会对某人有所帮助.

解:

global $post;
$prod_terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($prod_terms as $prod_term) {

    // gets product cat id
    $product_cat_id = $prod_term->term_id;

    // gets an array of all parent category levels
    $product_parent_categories_all_hierachy = get_ancestors( $product_cat_id, 'product_cat' );  



    // This cuts the array and extracts the last set in the array
    $last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true);
    foreach($last_parent_cat as $last_parent_cat_value){
        // $last_parent_cat_value is the id of the most top level category, can be use whichever one like
        echo '<strong>' . $last_parent_cat_value . '</strong>';
    }

}
Run Code Online (Sandbox Code Playgroud)


Mau*_*uro 25

或者这个:

$cat = get_the_terms( $product->ID, 'product_cat' );

foreach ($cat as $categoria) {
if($categoria->parent == 0){
   echo $categoria->name;
}
}
Run Code Online (Sandbox Code Playgroud)

  • 这种方法不会像它需要的那样沿着祖先链向上传播。不起作用。 (2认同)

tho*_*e51 7

我知道这是一个旧帖子,但我有类似的情况,我们需要获取当前产品的根类别.我能想到的最简单的解决方案是看看WooCommerce如何处理它的面包屑,这段代码就是我的诀窍:

if ( is_product() ) {
    global $post;
    $terms = wc_get_product_terms( $post->ID, 'product_cat', array( 'orderby' => 'parent', 'order' => 'DESC' ) );
    if ( ! empty( $terms ) ) {
        $main_term = $terms[0];
        $ancestors = get_ancestors( $main_term->term_id, 'product_cat' );
        if ( ! empty( $ancestors ) ) {
            $ancestors = array_reverse( $ancestors );
            // first element in $ancestors has the root category ID
            // get root category object
            $root_cat = get_term( $ancestors[0], 'product_cat' );
        }
        else {
            // root category would be $main_term if no ancestors exist
        }
    }
    else {
        // no category assigned to the product
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

这是我实际使用的解决方案

function get_parent_terms($term) {
    if ($term->parent > 0){
        $term = get_term_by("id", $term->parent, "product_cat");
        return get_parent_terms($term);
    }else{
        return $term->term_id;
    }
}
global $wp_query;
$cat_obj = $wp_query->get_queried_object();
$Root_Cat_ID = get_parent_terms($cat_obj);
Run Code Online (Sandbox Code Playgroud)