問題描述

reset_postdata 如何工作?文件説:

restore the global $post variable of the main query loop after a secondary query loop using new WP_Query

但是在該類中,它需要當前 WP_Query 實例的”current” 文檔,並將其設置為全局 $post 。那麼它如何恢復主查詢循環的帖子?

WP_Query 類。

最佳解決方案

WP_Query::reset_postdata()將全局後變量 ($GLOBALS['post'] === $post) 設置為當前 WP_Query 實例的循環中的當前帖子。

public function reset_postdata() {
    if ( ! empty( $this->post ) ) {
        $GLOBALS['post'] = $this->post;
        $this->setup_postdata( $this->post );
    }
}

這意味着,如果您在頁面上運行自定義查詢,$post 將保存該自定義查詢的循環中的最後一個帖子。你可以通過添加來測試自己

?><pre><?php var_dump($post); ?></pre><?php

直接在你的自定義查詢循環之後。

在循環後的主查詢中也是如此,$post 將在循環之前保存主查詢的最後一個帖子和循環中的第一個帖子。

這是一個簡單的測試來測試 $post 全局。您可以將其添加到您的函數文件中,並加載您網站上的任何頁面

add_action( 'wp_head', function()
{
    global $post;
    ?><pre><?php var_dump($post->ID); ?></pre><?php
}):
add_action( 'wp_footer', function()
{
    global $post;

    ?><pre><?php var_dump($post->ID); ?></pre><?php

    $q = new WP_Query( 'posts_per_page=3' );
    while ( $q->have_posts() ) {
        $q->the_post();

        ?><pre><?php var_dump($post->ID); ?></pre><?php
        the_title();

    }

    ?><pre><?php var_dump($post->ID); ?></pre><?php
    wp_reset_postdata();
    ?><pre><?php var_dump($post->ID); ?></pre><?php
});

So how does it restore the post of the main query loop?

這是通過調用 wp_reset_postdata()完成的,它將全局 $post 復位到主查詢循環中的當前帖子。如果您在主查詢循環之前或之後添加自定義查詢,這通常是最後一個帖子中的第一個。

讓我們來看看 wp_reset_postdata()如何做

function wp_reset_postdata() {
    global $wp_query;

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

如您所見,wp_reset_postdata()只是 WP_Query::reset_postdata()的封裝。這裏的重要部分是它是主查詢對象方法 $wp_query->reset_postdata(); 的包裝器。

記住,主查詢也使用 WP_Query 。這是主查詢對象的設置方式

/**
 * WordPress Query object
 * @global WP_Query $wp_the_query
 * @since 2.0.0
 */
$GLOBALS['wp_the_query'] = new WP_Query();

/**
 * Holds the reference to @see $wp_the_query
 * Use this global for WordPress queries
 * @global WP_Query $wp_query
 * @since 1.5.0
 */
$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];

那麼 wp_reset_postdata()是什麼,它需要主查詢對象中的當前帖子,並將其設置為 $post 全局,這就是 WP_Query::reset_postdata()如何將 $post 設置為主查詢的當前帖子

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。