the_post()WP 1.5.0

Sets the next post to the global $post variable. Also sets all post data with setup_postdata().

The global $post variable becomes the next post from the loop, see WP_Query::next_post(). If the loop has just started, the first post from the loop will be set to global $post.

Next, based on the seted global $post variable, all the important post data will be set - see setup_postdata( $post ).

Also, enables the WP_Query::in_the_loop = true property. This tells that the loop is running - we need this to make in_the_loop() function work properly.

This function should definitely be used in conjunction with have_posts() function, which checks if this function can be used.

while ( have_posts() ) {
	the_post();

	The_title();
}

This function only works with the global $wp_query object. So if you make a custom query, you need to call the method of the working object with the same name, instead of this function:

``php
$query = new WP_Query( $args );

while ( $query->have_posts() ) {
$query->the_post();

the_title(); // print the title of the post
}

wp_reset_postdata(); // IMPORTANT return global $post back

1 time — 0.000023 sec (very fast) | 50000 times — 0.03 sec (speed of light) | PHP 7.1.2, WP 4.7.3

No Hooks.

Return

null. Nothing.

Usage

the_post();

Basic Usage

if ( have_posts() ) {
	while ( have_posts() ) {

		the_post();
		?>

		

Examples

0

#1 How to use a function in the WordPress Loop

while( have_posts() ){
	the_post();

	echo '<h2>';
	the_title();
	echo '</h2>';
	the_content();
}
0

#2 How to use a function outside the WordPress Loop

It is not necessary to use the Loop on single post page like is_single() if (have_posts ()) { while (have_posts ()) ) {the_post ()) .... On these pages, the $post variable is responsible for one post, so part of the loop can be taken away:

<?php the_post(); ?>

<h1><?php the_title() ?></h1>

<?php the_content(); ?>

Notes

  • Global. WP_Query. $wp_query WordPress Query object.

Changelog

Since 1.5.0 Introduced.

the_post() code WP 6.1.1

function the_post() {
	global $wp_query;

	if ( ! isset( $wp_query ) ) {
		return;
	}

	$wp_query->the_post();
}