如何将滑块中同一作者关联帖子的抓取数量限制为4篇
两种方法限制最多显示4篇作者帖子
方法1:修改查询参数(推荐)
这是更高效的方式,直接让数据库仅返回4篇帖子,避免不必要的数据查询。找到你创建$query的代码(通常是new WP_Query(...)),添加posts_per_page参数:
$query = new WP_Query(array( 'author' => get_the_author_meta('ID'), // 确保是当前作者的查询 'posts_per_page' => 4, // 限制最多4篇 // 保留你原有的其他查询参数 ));
方法2:在循环内截断(适合无法修改查询的场景)
你的代码里已经写好了计数截断的逻辑,只是被注释掉了,取消注释即可。同时注意补全缺失的endwhile语句,否则会出现语法错误:
修改后的完整代码:
<div class="author-recent-posts small"> <div class="author-recent-posts__slider"> <?php $count = 0; ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <?php if($count >= 4) break; ?> <?php $thumb = array(get_template_directory_uri() . '/images/music-background.jpg'); if (has_post_thumbnail() ): $thumb = wp_get_attachment_image_src( get_post_thumbnail_id(), 'single-post-thumbnail' ); endif; $thumb = sprintf('style="background-image: url(\'%s\')"', esc_url($thumb[0])); ?> <?php $count += 1; ?> <div class="author-recent-post-item"> <div class="author-recent-post-item__inner"> <a class="author-recent-post-item__link" href="<?php echo esc_url(get_permalink()); ?>" rel="bookmark"> <span class="sr-only"><?php _e('Read more'); ?></span> </a> <figure class="author-recent-post-item__thumb" <?php echo $thumb; ?>></figure> <div class="author-recent-post-item__header"> <?php the_title('<h3 class="entry-title">', '</h3>'); ?> </div> </div> </div> <?php endwhile; ?> </div> </div>
内容的提问来源于stack exchange,提问作者Patrik Madani
相关产品推荐
相关产品推荐

