循环WordPress博客文章


Loop WordPress blog posts

<?php get_header(); ?>
<div class="page-wrap group">
<div class="grid">
  <?php query_posts('showposts=6'); ?>
    <?php if (have_posts()): ?>
  <section class="blog-posts col-2-3 grid-pad">
    <?php while (have_posts()) : the_post(); ?>
      <article class="module" id="post-<?php the_ID(); ?>">
        <h2> <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a </h2>
        <p><time datetime="2001-05-15 19:00"><?php echo date('l jS F Y')?></p>
        <?php the_excerpt(); ?>

      </article>
      <?php endwhile; ?>
  </section>

这是我的index.php代码,我想做的是在<section class="blog-posts col-2-3 grid-pad">中发布3篇博客文章,然后在<section class="blog-posts col-2-3 grid-pad"> 中再发布3篇文章

那么,你如何循环这些帖子,让它们分布在整个页面上呢?现在我只能得到它,这样它就可以在第一个中显示所有内容

只需使用一个计数器变量:

<?php if (have_posts()): ?>
  <section>
  <?php $i = 0; while (have_posts()) : the_post(); ?>
      <article>
      ...
      <article>
  <?php if(++$i === 3): // close previous and open new one ?>
  </section>
  <section>
  <?php endif; ?>      
  <?php endwhile; ?>
  </section>    
<?php endif; ?>

或者,您可以使用WP_Query类执行两个查询,在第二个查询中使用posts_per_page=3参数和offset=3参数。


要更改页面上显示的帖子数量,请将其添加到您的功能文件中:

add_action('pre_get_posts', function($query){
  if(is_admin() || !$query->is_main_query())
    return;
  if(is_home()) // or whatever page you want the limit applied to
    $query->set('posts_per_page', 6);
});