我的目标是在每四篇文章之后打印一些额外的html。
以下代码有什么问题
<?php while ( have_posts() ) : the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php
$posts = $wp_query->post_count;
if ( $posts == 4 ) {
echo '<div class="clearfix"></div>';
}
?>
<?php endwhile; // end of the loop. ?>
以循环的基本代码为例,您可以包括一个计数器,在每次迭代中递增它,并检查它是否为零。
<?php if ( have_posts() ) : $count = 1; ?>
<?php while ( have_posts() ) : the_post();?>
<!-- do stuff ... -->
<?php if ( $count % 4 == 0 ): ?>
<!-- extra stuff every four posts -->
<?php endif; ?>
<?php $count++; endwhile; ?>
<?php endif; ?>
我知道这个问题已经得到了回答,但我认为有更干净的方法可以做到这一点。
您可以使用WP_查询对象中的几个有用属性,而不必添加自定义递增器。
<?php
// Do not forget this part, required if you do not define a custom WP_Query
global $wp_query;
// Below you can find some useful properties in the WP_Query object
// Use them to their full potential
// Gets filled with the requested posts from the database.
echo $wp_query->posts;
// The number of posts being displayed.
echo $wp_query->post_count;
// The total number of posts found matching the current query parameters
echo $wp_query->found_posts;
// The total number of pages. Is the result of $found_posts / $posts_per_page
echo $wp_query->max_num_pages;
// Index of the post currently being displayed. (Can only be used within the loop)
while( have_posts() ) : the_post();
echo $wp_query->current_post;
endwhile;
在使用$current_post属性时,您的循环将如下所示。
<?php global $wp_query; ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php
if ( ( $wp_query->current_post + 1 ) % 4 === 0 ) {
echo '<div class="clearfix"></div>';
}
?>
<?php endwhile; // end of the loop. ?>
我相信这是一个好的和干净的解决方案。
请在此处阅读有关WP_查询对象的更多信息:https://codex.wordpress.org/Class_Reference/WP_Query
试试这个
<?php
$count = 1;
while ( have_posts() ) : the_post();
wc_get_template_part( 'content', 'product' );
if ( $count%4==0 ) {
echo '<div class="clearfix"></div>';
}
$count++;
endwhile; ?>