Php 从WP_查询循环中的产品变体获取Woocommerce产品类别
嗨,我正试图显示产品种类的产品变化。下面的代码在我使用Php 从WP_查询循环中的产品变体获取Woocommerce产品类别,php,wordpress,woocommerce,custom-taxonomy,variations,Php,Wordpress,Woocommerce,Custom Taxonomy,Variations,嗨,我正试图显示产品种类的产品变化。下面的代码在我使用post\u type=product时起作用并显示产品类别,但如果我使用post\u type=product\u变体,则不显示任何内容 $args = array( 'post_type' => 'product_variation', 'posts_per_page' => -1, 'orderby' => 'rand' ); $loop = new WP_Query( $args );
post\u type=product
时起作用并显示产品类别,但如果我使用post\u type=product\u变体
,则不显示任何内容
$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(); ?>
$args=array('post_type'=>'product_variation','posts_per_page'=>-1,'orderby'=>'rand');
$loop=新的WP_查询($args);
而($loop->have_posts()):$loop->the_post();全球$product;?>
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_类型的“产品”和“产品变化”,您可以使用以下内容:
$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);
如果您有来自产品变体的WC_Product
对象实例,还可以使用
最后,在代码中,这一行是错误的,可以删除:
$post_categories = wp_get_post_categories( $loop->post->ID );
As
wp\u get\u post\u categories()
函数用于获取普通WordPress博客文章的类别术语,但不用于产品类别自定义分类法。您是否设置了名为“产品变体”的自定义文章类型?在你的functions.php或插件中?@DerekNolan:它的默认自定义帖子类型来自Woocommerce:从查看该文档来看,产品变体似乎没有默认的分类法。你有一些自定义分类设置吗?谢谢Loic。你的生活更安全:-)