在 WP_Query 循环中从产品变体中获取 Woocommerce 产品类别

Get Woocommerce Product Categories from Product variations in a WP_Query loop

您好,我正在尝试显示产品变体的产品类别。下面的代码在我使用 post_type=product 时有效并显示产品类别,但如果我使用 post_type=product_variation.

则不显示任何内容
        $args = array( 'post_type' => 'product_variation', 'posts_per_page' => -1, 'orderby' => 'rand' );
        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<?php

?>

                <li class="product">    

                    <a href="<?php echo get_permalink( $loop->post->ID ) ?>" title="<?php echo esc_attr($loop->post->post_title ? $loop->post->post_title : $loop->post->ID); ?>">

                        <?php woocommerce_show_product_sale_flash( $post, $product ); ?>

                        <?php if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); else echo '<img src="'.woocommerce_placeholder_img_src().'" alt="Placeholder" width="300px" height="300px" />'; ?>

                        <h3><?php the_title(); ?></h3>

                        <span class="price"><?php echo $product->get_price_html(); ?></span> 
                        <?php
                        $post_categories = wp_get_post_categories( $loop->post->ID  );
                        var_dump( $post_categories);
                          global $post;
                         // get categories
                          $terms = wp_get_post_terms( $post->ID, 'product_cat' );
                          foreach ( $terms as $term ) $cats_array[] = $term->term_id;

                          var_dump($cats_array);
                        ?>

                    </a>

                </li>
    <?php endwhile; ?>
    <?php wp_reset_query(); ?>

Woocommerce 产品变体 不处理任何 自定义分类 作为产品类别、产品标签甚至正常的产品属性。

相反,您需要通过这种方式获取父可变产品:

$terms = wp_get_post_terms( $loop->post->post_parent, 'product_cat' );
foreach ( $terms as $term )
    $cats_array[] = $term->term_id;

var_dump($cats_array);

您甚至可以使用以下方法使其更紧凑、更轻便:

 $cats_array = wp_get_post_terms( $loop->post->post_parent, 'product_cat', array("fields" => "ids") );

var_dump($cats_array);

这次它将适用于您的产品变体。

要使其同时适用于 post_type "product" 和 "product_variation",您可以使用以下内容:

$the_id = $loop->post->post_parent > 0 ? $loop->post->post_parent : $loop->post->ID;

$cats_array = wp_get_post_terms( $the_id, 'product_cat', array("fields" => "ids") );

var_dump($cats_array);

If you have the WC_Product object instance from a Product variation, you can also get the parent variable product ID using WC_Product get_parent_id() method

最后,在您的代码中,这一行 是错误的,可以删除:

$post_categories = wp_get_post_categories( $loop->post->ID  );

因为 wp_get_post_categories() 函数用于获取普通 WordPress 博客的类别术语 post,但不适用于产品类别自定义分类法。