显示网页.Div 在 Wordpress 循环中的第 n 个帖子之后


Display html.Div after nth post within Wordpress loop

使用自定义wordpress循环:

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

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

我在循环遍历每个结果之前定义了$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。

WordPress在

The Loop中使用对象WPQuery,在该对象中,您有两个变量可用于确定您将在页面上显示的帖子数量。如果像这样声明 $wp_query $wp_query = new WP_Query( $args );,则变量$wp_query->post_count;$wp_query->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; ?>