wordpress调用指定自定义分类法的分类文章

WordPress教程 4523

wordpress注册自定义文章类型和自定义分类法后,不仅仅只在wordpress主题主循环中调用,还会有在网站的某个位置调用指定自定义分类法的某个分类文章的需求,那么要怎么调用?其实和普通post文章的调用方法一致,只是需要多设置一个tax_query参数。

方法一:通过get_posts函数调用

把下面代码添加到要显示分类文章的模板位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php 
	$posts = get_posts(array(							
		'numberposts' => '10', //输出的文章数量
		'post_type' => 'product',	//自定义文章类型名称		
		'tax_query'=>array(
			array(
				'taxonomy'=>'products', //自定义分类法名称
				'terms'=>'10' //id为64的分类。也可是多个分类array(12,64)
			)
		),
	)
	);		
?>
<ul>
<?php if($posts): foreach($posts as $post): ?>			
	<li><a href="<?php the_permalink(); ?>" target="_blank" title="<?php the_title();?>"><?php the_title();?></a></li>
<?php wp_reset_postdata(); endforeach; endif;?>
</ul>
方法二:通过强大的WP_Query函数调用

把下面代码添加到要显示分类文章的模板位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php 
    $args = array(
        'post_type' => 'product', //自定义文章类型名称
        'showposts' => 10,
        'tax_query' => array(
            array(
                'taxonomy' => 'products',//自定义分类法名称
                'terms' => 64 //id为64的分类。也可是多个分类array(12,64)
                ),
            )
        );
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
        while ($my_query->have_posts()) : $my_query->the_post();
?>       
	<li><a href="<?php the_permalink(); ?>" target="_blank" title="<?php the_title();?>"><?php the_title();?></a></li>
<?php endwhile; wp_reset_query(); } ?>

参数说明:

  • post_type 要调用的自定义文章类型的名称(必须和要调用的自定义分类法关联)
  • taxonomy 要调用的自定义分类法的名称
  • terms 要调用的自定义分类法下创建的分类目录ID

精品推荐: