我们在主题开发过程中,如果用到了自定义文章类型,有时候我们还需要去获取自定义文章类型的相关文章,比如你创建了一个product自定义文章类型,和其对应的自定义分类法是product_category。那么,如果我们需要在产品详情页获取相关产品的话,我们就可以使用一下代码:
<?PHP
$terms = get_the_terms( $post->ID,'product_category','string');/**product_category是你的自定义分类法的名字**/
$term_ids = wp_list_pluck($terms,'term_id');
$second_query = new WP_Query( array(
'post_type' => 'product',/**product是你自定义文章类型的名字**/
'tax_query' => array(
array(
'taxonomy' => 'product_category',/**product_category是你自定义分类法的名字**/
'field' => 'id',
'terms' => $term_ids,
'operator'=> 'IN' //Or 'AND' or 'NOT IN'
)),
'posts_per_page' => 4,
'ignore_sticky_posts' => 1,
'orderby' => 'rand',
'post__not_in'=>array($post->ID)
) );
?>
<?PHP if($second_query->have_posts())?>
<?PHP while ($second_query->have_posts() ) : $second_query->the_post();?>
<?PHP endwhile; wp_reset_query();?>