从 Woocommerce 中的产品 ID 列出产品类别层次结构

mrD*_*mrD 3 php wordpress product custom-taxonomy woocommerce

我有一个可以属于多个类别的产品,例如看一下以下字符串:

  • 类别1>产品1
  • 类别1>产品2
  • 类别 2>子类别 1>产品 1
  • 类别 3>子类别 1>子类别 2>产品 1

在 woocommerce 中,如果我有一个 ProductID,我可以执行以下操作:

    function alg_product_categories_names2( $atts ) {
    $product_cats = get_the_terms( $this->get_product_or_variation_parent_id( $this->the_product ), 'product_cat' );
    $cats = array();

    $termstest= '';
    if ( ! empty( $product_cats ) && is_array( $product_cats ) ) {
        foreach ( $product_cats as $product_cat ) {             
            if ( $term->parent == 0 ) { //if it's a parent category
                    $termstest .= ' PARENTCAT= '. $product_cat->name;
          }                             
        }
    }

    return htmlentities('<categories_names>'. $termstest .'</categories_names>');
}
Run Code Online (Sandbox Code Playgroud)

但这只是返回产品 ID 的所有父类别。

类别 1、类别 2、子类别 1、类别 3、子类别 2

我很难受这个问题。我需要的是给定一个产品 ID,构建上面的列表 - 应该返回的是:

“类别1>产品1”| “类别 2>子类别 1>产品 1”| “类别3>子类别1>子类别2>产品1”

我基本上需要从产品 ID 重建每个类别路径。

Loi*_*tec 8

要获取某个产品类别的所有祖先,可以使用Wordpressget_ancestors()功能

以下自定义短代码函数将为给定产品的每个产品类别输出,以及问题中定义的字符串中具有产品类别的祖先:

add_shortcode( 'product_cat_list', 'list_product_categories' )
function list_product_categories( $atts ){
    $atts = shortcode_atts( array(
        'id' => get_the_id(),
    ), $atts, 'product_cat_list' );

    $output    = []; // Initialising
    $taxonomy  = 'product_cat'; // Taxonomy for product category

    // Get the product categories terms ids in the product:
    $terms_ids = wp_get_post_terms( $atts['id'], $taxonomy, array('fields' => 'ids') );

    // Loop though terms ids (product categories)
    foreach( $terms_ids as $term_id ) {
        $term_names = []; // Initialising category array

        // Loop through product category ancestors
        foreach( get_ancestors( $term_id, $taxonomy ) as $ancestor_id ){
            // Add the ancestors term names to the category array
            $term_names[] = get_term( $ancestor_id, $taxonomy )->name;
        }
        // Add the product category term name to the category array
        $term_names[] = get_term( $term_id, $taxonomy )->name;

        // Add the formatted ancestors with the product category to main array
        $output[] = implode(' > ', $term_names);
    }
    // Output the formatted product categories with their ancestors
    return '"' . implode('" | "', $output) . '"';
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(活动主题)的 function.php 文件中。经过测试并有效。


用法:

1)在产品页面的php代码中:

echo do_shortcode( "[product_cat_list]" );
Run Code Online (Sandbox Code Playgroud)

2)在具有给定产品ID的php代码中(这里以产品ID37为例)

echo do_shortcode( "[product_cat_list id='37']" );
Run Code Online (Sandbox Code Playgroud)

我认为您的输出中不需要产品名称,因为它是重复的(在每个产品类别上)。所以你会得到这样的东西:

"Cat1" | "Cat2>subcat1" | "Cat3>subcat1>subcat2"
Run Code Online (Sandbox Code Playgroud)

  • 我必须反转 get_ancestors 输出的数组,以使我的层次结构处于正确的顺序,但除此之外,这段代码非常有用,并节省了我很多时间。谢谢。 (2认同)