这是关于 WooCommerce 单一产品页面。我正在尝试使用产品类别来显示相关产品。我可以用下面的代码显示它。使用此功能将包括当前帖子并且仅显示产品。
<?php
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term ) {
$product_cat_name = $term->name;
break;
}
$ids = array();
$currentID = get_the_ID();
$args = array('post_type' => 'product', 'product_cat' => $product_cat_name);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product;
$ids[] = $loop->post->ID;
endwhile;
wp_reset_query();
print_r($ids);
?>
但我试图阻止当前产品显示在相关产品上。我尝试使用下面代码的第一秒,但它没有排除,而是检索所有默认帖子。
<?php
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term ) {
$product_cat_name = $term->name;
break;
}
$ids = array();
$currentID = get_the_ID();
$args = array('post_type' => 'product', 'product_cat' => $product_cat_name, 'post__not_in' => array($currentID));
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product;
$ids[] = $loop->post->ID;
endwhile;
wp_reset_query();
print_r($ids);
?>
我怎样才能实现这个目标?
谢谢
最佳答案
根据您的第一个代码片段,这应该可行,并且将避免在基于当前产品类别的相关产品中显示您当前的产品。
这是代码:
<?php
global $post;
$ids = array();
// Get the "main" product category
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ){
if($term->parent != 0) {
$product_cat_name = $term->name;
break; // stop the loop
}
// The Query
$loop = new WP_Query( array(
'post_type' => 'product',
'product_cat' => $product_cat_name,
'post__not_in' => array($post->ID) // Avoid displaying current product
) );
if ( $loop->have_posts() ):
while ( $loop->have_posts() ) : $loop->the_post();
$ids[] = $loop->post->ID; // Set all other product IDs for that product category
endwhile;
endif;
wp_reset_query();
// Raw output
print_r($ids);
?>
这应该有效......
关于php - 单一产品页面 - 从相关产品中排除当前产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38932196/