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

时间:2018-07-11 12:47:41

标签: php wordpress woocommerce custom-taxonomy variations

您好我正在尝试显示产品变体的产品类别。下面的代码可以正常工作,并在我使用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(); ?>

1 个答案:

答案 0 :(得分:1)

Woocommerce 产品变体不处理任何自定义分类作为产品类别,产品标签甚至常规的产品属性。<​​/ p>

相反,您将需要通过以下方式获取父变量产品:

$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);
  

如果您具有Product变体中的WC_Product对象实例,则还可以使用WC_Product get_parent_id() method

获取父变量product ID。

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

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

使用wp_get_post_categories()函数可以获取普通WordPress博客文章的类别术语,而不是产品类别的自定义分类法。

相关问题