category.php 中的自定义帖子数量

Custom amount of posts in category.php

我想在 category.php 中设置不同数量的帖子。我想分页显示每页 15 篇文章。

我正在使用二十四主题。我怎样才能做到这一点?

我的代码是:

 
<?php
 
get_header(); ?>

 <section id="primary" class="content-area">
  <div id="content" class="site-content" role="main">
  
 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); 
  

 ?>
  
   <div class="post-cat">
    
<?php 
if ( has_post_thumbnail() ) { 
 the_post_thumbnail();
} 
?>
  <h2><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> 
<p><?php the_category( ', ' ); ?></p>
 <?php endwhile; else : ?> 
  <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>

 
 <?php endif; ?>
  </div><!-- #content -->
 </section><!-- #primary -->

<?php
get_sidebar( 'content' );
get_sidebar();
get_footer();

试试这个代码。

<?php

get_header(); ?>

    <section id="primary" class="content-area">
        <div id="content" class="site-content" role="main">

 <?php 

$query = new WP_Query(array(
    'posts_per_page'   => 15
));


 if ( have_posts() ) : while ($query->have_posts()): $query->the_post(); 


 ?>

        <div class="post-cat">

<?php 
if ( has_post_thumbnail() ) { 
    the_post_thumbnail();
} 
?>
    <h2><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> 
<p><?php the_category( ', ' ); ?></p>
 <?php endwhile; else : ?> 
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>


 <?php endif; ?>
        </div><!-- #content -->
    </section><!-- #primary -->

<?php
get_sidebar( 'content' );
get_sidebar();
get_footer();


 ?>

一切都已在 twentyfourteen 中进行了很好的设置,因此您无需使用自定义查询修改任何内容。

这是你应该做的:

  • 创建一个 child theme 以便您可以进行修改,以免丢失任何更新工作

  • 使用 pre_get_posts 调整类别页面上的主查询,使每页显示 15 个帖子。

将以下内容添加到您的子主题 functions.php 或自定义插件(请注意,由于使用闭包)

add_action( 'pre_get_posts', function ( $query )
{
    if ( !is_admin() && $query->is_main_query() && $query->is_category() ) {
        $query->set( 'posts_per_page', 15 );
    }
});