Home  >  Article  >  Backend Development  >  wordpress首页如何实现分类显示文章

wordpress首页如何实现分类显示文章

WBOY
WBOYOriginal
2016-06-06 20:22:501602browse

想在首页只显示指定分类的文章,在网上找到的方法是

<code><?php while( have_posts()): the_post();update_post_caches($posts);?> 
<?php if(in_category('diary')):?> 
<div class="post"> 
……循环体结构代码……
</div> 
<?php endif;?> 
<?php endwhile;?>
<?php pagination($query_string); ?>
</code>

但是我的首页是一页显示一篇文章,采用这个方法的话,如果我有四篇文章,两篇是diary类,两篇不是该类,首页虽然的确显示了diary类的文章,但是页码显示是有4页,请问这个页码问题怎么解决?

回复内容:

想在首页只显示指定分类的文章,在网上找到的方法是

<code><?php while( have_posts()): the_post();update_post_caches($posts);?> 
<?php if(in_category('diary')):?> 
<div class="post"> 
……循环体结构代码……
</div> 
<?php endif;?> 
<?php endwhile;?>
<?php pagination($query_string); ?>
</code>

但是我的首页是一页显示一篇文章,采用这个方法的话,如果我有四篇文章,两篇是diary类,两篇不是该类,首页虽然的确显示了diary类的文章,但是页码显示是有4页,请问这个页码问题怎么解决?

应该这样:

<code>add_action( 'pre_get_posts', 'wpdit_pre_get_posts' );
function wpdit_pre_get_posts( $wp_query ) {
    if ( is_home() || is_front_page() ){
        $wp_query->set( 'category__in', array(1) );
    }
    return $wp_query;
}</code>

你的需求是“首页只显示指定分类的文章”,所以要事先在首页只获取指定分类下的文章;
而非提出全部文章再去判断哪个该在首页显示或不显示。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn