have_posts()
云策文档标注
概述
have_posts() 函数用于检查当前 WordPress 查询中是否有可供循环的帖子。它基于全局 $wp_query 对象,返回布尔值表示帖子是否可用。
关键要点
- 函数返回布尔值:true 表示有帖子可循环,false 表示循环结束。
- 内部调用 $wp_query->have_posts() 方法,检查 WP_Query 对象中的帖子状态。
- 当没有更多帖子时,会触发 loop_end 动作并调用 rewind_posts() 方法。
- 在循环内调用此函数可能导致无限循环,需谨慎使用。
代码示例
if ( have_posts() ) :
while ( have_posts() ) : the_post();
// Your loop code
endwhile;
else :
_e( 'Sorry, no posts were found.', 'textdomain' );
endif;注意事项
- 避免在循环内调用 have_posts(),以防止无限循环问题。
- 对于自定义 WP_Query 对象,应使用 $query->have_posts() 而非全局函数。
原文内容
Determines whether current WordPress query has posts to loop over.
Source
function have_posts() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
return false;
}
return $wp_query->have_posts();
}
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 5 content
Codex
Default use:
The following example can be used to determine if any posts exist and loop through them if they do.
if ( have_posts() ) : while ( have_posts() ) : the_post(); // Your loop code endwhile; else : _e( 'Sorry, no posts were found.', 'textdomain' ); endif;Skip to note 6 content
Codex
Avoiding infinite loops:
Calling this function within the loop will cause an infinite loop. For example, see the following code:
while ( have_posts() ) : the_post(); // Display post if ( have_posts() ) : // If this is the last post, the loop will start over // Do something if this isn't the last post endif; endwhile;If you want to check if there are more posts in the current loop without this unfortunate side effect, you can use this function:
In your
functions.phpfile:/** * Check if a loop has any more posts left. * * @global $wp_query * * @return bool True if there are any more posts in this loop, false if not. */ function wpdocs_has_more_posts() { global $wp_query; return $wp_query->current_post + 1 < $wp_query->post_count; }In your template file:
while ( have_posts() ) : the_post(); // Display post if ( wpdocs_has_more_posts() ) : // Do something if this isn't the last post endif; endwhile;Skip to note 7 content
Muhammad Jawad Abbasi
<h1></h1> <a href="<?php the_permalink(); ?>"> </a> <p></p>Output:
Post title
Post featured full size image (When anyone click on the image then open post single page)
Post small description
Edited by @audrasjb: Small WPCS fixes.
Skip to note 8 content
johnhawley
Example: if creating a custom WP_Query out of the standard WP loop context. This example uses
have_posts()function extended fromWP_Query:'custom_post_type'); // Execute query $cpt_query = new WP_Query($args); // Create cpt loop, with a have_posts() check! if ($cpt_query->have_posts()) : while ($cpt_query->have_posts()) : $cpt_query->the_post(); ?>