wp_reset_postdata()恢复$post全局变量的数据

目录

描述

Use this function to restore the global $post variable of the main query loop after a secondary query loop using new WP_Query. It restores the $post variable to the current post in the main query.

Differences between the main query loop and secondary query loops are:

  • the main loop is based on the URL request and is processed before templates are loaded
  • secondary loops are queries (using new WP_Query) in theme template or plugin files

wp_reset_postdata() 描述

用法

<?php wp_reset_postdata(); ?>

wp_reset_postdata() 用法

参数

This function does not accept any parameters.

wp_reset_postdata() 参数

返回值

This function does not return any values.

wp_reset_postdata() 返回值

示例

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php
// example args
$args = array( 'posts_per_page' => 3 );

// the query
$the_query = new WP_Query( $args );
?>

<?php if ( $the_query->have_posts() ) : ?>

	<!-- start of the loop -->
	<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
		<?php the_title(); ?>
		<?php the_excerpt(); ?>
	<?php endwhile; ?><!-- end of the loop -->

	<!-- put pagination functions here -->
	<?php wp_reset_postdata(); ?>

<?php else:  ?>

<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>

<?php endif; ?>

wp_reset_postdata() 示例

注意

  • 使用到: $wp_query

wp_reset_postdata() 注意

历史

  • 添加于 版本: 3.0.0

wp_reset_postdata() 历史

源文件

wp_reset_postdata() 函数的代码位于 wp-includes/query.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * After looping through a separate query, this function restores
 * the $post global to the current post in the main query.
 *
 * @since 3.0.0
 *
 * @global WP_Query $wp_query
 */
function wp_reset_postdata() {
	global $wp_query;

	if ( isset( $wp_query ) ) {
		$wp_query->reset_postdata();
	}
}

wp_reset_postdata() 源文件

相关