【问题标题】:Display html.Div after nth post within Wordpress loop在 Wordpress 循环中的第 n 个帖子后显示 html.Div
【发布时间】:2016-01-30 14:38:03
【问题描述】:

使用自定义 wordpress 循环:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
//Post Content
<?php endwhile;?>
//Pagination
<?php else : ?>
//No posts message
<?php endif; ?>

我需要帮助重组代码以显示 html Div.block 在每个页面第 4 次发布后,条件是该页面至少有 6 个要显示的帖子。

【问题讨论】:

    标签: php wordpress loops


    【解决方案1】:

    我在循环每个结果之前定义了$postnum,这样$postnum 的原始值可以在每次迭代中递增。

    <?php 
    $postnum = 0; // Set counter to 0 outside the loop
    if (have_posts()) : while (have_posts()) : the_post();
    ?>
      //Post Content
    <?php $postnum++; // Increment counter
    if ($postnum == 4){ ?>
      //Div.block
    <?php } ?>
    <?php endwhile;?>
      //Pagination
    <?php else : ?>
      //No posts message
    <?php endif; ?>
    

    这样,我能够在循环内每个页面上的第 4 个帖子后显示单个 Div.block html。

    【讨论】:

      【解决方案2】:

      WordPress 在 The Loop 中使用对象 WPQuery,在该对象中,您有两个变量可用于确定您将在页面上显示的帖子数量。如果您像这样声明 $wp_query $wp_query = new WP_Query( $args );,则变量是 $wp_query-&gt;post_count; 和 $wp_query-&gt;found_posts;。

      现在,我将在你的循环中添加一个小计数器,它会变成这样:

      <?php 
      $size = $wp_query->post_count;
      $counter = 0;
      if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
      //Post Content
          if ($size >= 6 && $counter == 3) {
              //show your div here
          }
      
          $counter++;
      <?php endwhile;?>
          //Pagination
      <?php else : ?>
          //No posts message
      <?php endif; ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多