我的目标是在每四个帖子后打印一些额外的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. ?>
Run Code Online (Sandbox Code Playgroud)
使用The Loop的基本代码,您可以包含一个计数器,在每次迭代时递增它并检查其零模块是否为4.
<?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; ?>
Run Code Online (Sandbox Code Playgroud)
我知道这个问题已经得到了回答,但我认为有更简洁的方法可以做到这一点。
您可以使用 WP_Query 对象中有几个有用的属性,而不必添加自定义增量器。
<?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;
Run Code Online (Sandbox Code Playgroud)
在使用 $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. ?>
Run Code Online (Sandbox Code Playgroud)
我相信这是一个好的和干净的解决方案。
在此处阅读有关 WP_Query 对象的更多信息:https ://codex.wordpress.org/Class_Reference/WP_Query
| 归档时间: |
|
| 查看次数: |
2016 次 |
| 最近记录: |