【发布时间】:2018-12-06 07:34:08
【问题描述】:
我需要按分类更改相关产品,如果分类没有足够的产品,则显示其他分类的其余产品。
我有 2 个分类; product_tag 和 product_cat。有时 product_tag 中的产品不超过 4 个,因此我需要使用另一个分类来满足相关产品中的 4 个产品。
所以我需要 4 个相关产品,如果 product_tag 全部有那么什么都没有,如果没有使用 product_cat 来完成 4 个产品。
任何帮助都会很棒。
<?php
// get the custom post type's taxonomy terms
$related_category = wp_get_object_terms( $post->ID, 'product_cat', array('fields' => 'ids') );
$related_tag = wp_get_object_terms( $post->ID, 'product_tag', array('fields' => 'ids') );
// arguments
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 4, // you may edit this number
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'product_tag',
'field' => 'id',
'terms' => $related_tag
)
),
'post__not_in' => array ($post->ID),
);
$related_items = new WP_Query( $args );
// loop over query
if ($related_items->have_posts()) :
while ( $related_items->have_posts() ) : $related_items->the_post();
?>
<div class="related_item">
<div class="Related_image">
<a href="<?php the_permalink() ?>"><?php the_post_thumbnail('thumbnail'); ?></a>
</div>
<div class="Related_title">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><h2>
</div>
</div>
<?php
endwhile;
endif;
// Reset Post Data
wp_reset_postdata();
?>
【问题讨论】:
标签: php wordpress woocommerce taxonomy related-posts