函数文档

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.

Return

bool True if posts are available, false if end of the loop.

More Information

This function checks whether there are more posts available in the main WP_Query object to loop over. It calls <a href="https://developer.wordpress.org/reference/classes/wp_query/have_posts/">have_posts()</a> method on the global $wp_query object.

If there are no more posts in the loop, it will trigger the loop_end action and then call call rewind_posts() method.

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.

User Contributed Notes

  1. Skip to note 6 content

    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.php file:

    /**
     * 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;

  2. Skip to note 8 content

    Example: if creating a custom WP_Query out of the standard WP loop context. This example uses have_posts() function extended from WP_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(); ?>