WordPress获取指定分类文章的方法

在很多时候我们需要在特殊的地方调用指定分类中的文章,可能是首页,也可能是某个特殊的页面,这里用的方法就是自定义WP_Query查询,WP_Query是wordpress主题提供的一个类,它有丰富的参数配置,并且使用非常灵活,我爱主题网通过WP_Query类可以创建自己所需要的wordpress循环输出,比如调用最新发布的信息、置顶文章自定义文章类型等,和query_posts()函数具有异曲同工之妙,但比query_posts()函数查询更快。

通过WP_Query获取指定分类文章的之一:

  1. 通过分类的ID来获取,代码如下
<?php while( have_posts()): the_post();update_post_caches($posts);?>
<?php if(in_category('5')):?>
<div class="post">
这里是你的html结构
</div>
<?php endif;?>
<?php endwhile;?>

通过代码中的ID号5修改成你想要的分类ID即可。

  1. 还有一种方法是同分类的名称来获取指定分类中的文章,代码如下
<?php
$args = array(
    'category_name' => '新闻中心',
);

$hx_posts = new WP_Query($args);

if ($hx_posts -> have_posts() ) :
    while ($hx_posts -> have_posts() ) : $hx_posts -> the_post();
        ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php
    endwhile;
endif;
wp_reset_postdata();
?>

这段代码就会获取指定的新闻中心分类中的文章,使用起来也很方便。

  1. 如果你想在首页不显示指定分类的文章,可以通过下面的代码来控制:
add_filter( 'pre_get_posts', 'hx_exclude_category_home' );
function hx_exclude_category_home( $query ) {
    if ( $query->is_home ) {
        $query->set( 'cat', '-1, -3' );
    }
    return $query;
}

将其添加到主题函数库functions.php中即可。

我爱主题网 自2012
主题:260+ 销售:1000+
兼容浏览器

电话咨询

7*12服务咨询电话:

133-7205-6573

微信咨询