wordpress调用指定自定义分类法的分类文章
网站文章 2026-09-21 07:08:40 3 0

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
文章说明
本文标签:
©版权声明
本站提供的一切软件、教程和游戏辅助仅限用于娱乐和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络收集,版权争议与本站无关。如有侵权请邮件与我们联系处理。敬请谅解!6594404@qq.com