WP_Query::have_posts() WordPress Method

The have_posts() method is a boolean method that will return true if there are posts still available to iterate over in a WP_Query instance, and false if there are no more posts. This is useful when you need to loop over a number of posts in a WP_Query instance, and you want to check if there are any posts left before continuing.

WP_Query::have_posts() #

Determines whether there are more posts available in the loop.


Description

Calls the ‘loop_end’ action when the loop is complete.


Top ↑

Return

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


Top ↑

Source

File: wp-includes/class-wp-query.php

	public function have_posts() {
		if ( $this->current_post + 1 < $this->post_count ) {
			return true;
		} elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
			/**
			 * Fires once the loop has ended.
			 *
			 * @since 2.0.0
			 *
			 * @param WP_Query $query The WP_Query instance (passed by reference).
			 */
			do_action_ref_array( 'loop_end', array( &$this ) );
			// Do some cleaning up after the loop.
			$this->rewind_posts();
		} elseif ( 0 === $this->post_count ) {
			/**
			 * Fires if no results are found in a post query.
			 *
			 * @since 4.9.0
			 *
			 * @param WP_Query $query The WP_Query instance.
			 */
			do_action( 'loop_no_results', $this );
		}

		$this->in_the_loop = false;
		return false;
	}


Top ↑

Changelog

Changelog
VersionDescription
1.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More