【问题标题】:Loop WordPress blog posts循环 WordPress 博客文章
【发布时间】:2013-02-06 13:40:04
【问题描述】:
<?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 代码,我想做的是在 &lt;section class="blog-posts col-2-3 grid-pad"&gt; 中写 3 篇博文,然后在 &lt;section class="blog-posts col-2-3 grid-pad"&gt; 中写另外 3 篇博文

那么,如何循环发布帖子,以便让它们在页面上散布?现在我只能得到它,所以它会在第一个显示它们

【问题讨论】:

  • 当然可以。也会坐在右边。

标签: php html wordpress loops


【解决方案1】:

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

<?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);

});

【讨论】:

  • 谢谢,最后一个问题,我将如何限制页面上的帖子数量?例如,我只想要侧栏中的 3 个帖子?换句话说,整个页面上的帖子数量最多。
  • query_posts('showposts=6'); 放在上面,就像你做的那样,应该强制一个最大值。 6 个帖子的数量
  • 之前试过了,还是不行。我把它放在和上次一样的位置,似乎没有效果。
  • 精彩。一个顶级的答案。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 2017-09-26
  • 2015-10-05
  • 1970-01-01
相关资源
最近更新 更多