問題描述

我對 pre_get_posts 在真實頁面和靜態首頁上的使用做了相當廣泛的研究,似乎沒有愚蠢的方法。

我發現的最好的選擇是從 post done by @birgire on Stackoverflow 。我已經將其重寫成一個演示類,並使程式碼更有活力

class PreGeTPostsForPages
{
    /**
     * @var string|int $pageID
     * @access protected     
     * @since 1.0.0
     */
    protected $pageID;

    /**
     * @var bool $injectPageIntoLoop
     * @access protected     
     * @since 1.0.0
    */
    protected $injectPageIntoLoop;

    /**
     * @var array $args
     * @access protected     
     * @since 1.0.0
     */
    protected $args;

    /**
     * @var int $validatedPageID
     * @access protected     
     * @since 1.0.0
     */
    protected $validatedPageID = 0;

    /**
     * Constructor
     *
     * @param string|int $pageID = NULL
     * @param bool $injectPageIntoLoop = false
     * @param array| $args = []
     * @since 1.0.0
     */     
    public function __construct( 
        $pageID             = NULL, 
        $injectPageIntoLoop = true, 
        $args               = [] 
    ) { 
        $this->pageID             = $pageID;
        $this->injectPageIntoLoop = $injectPageIntoLoop;
        $this->args               = $args;
    }

    /**
     * Private method validatePageID()
     *
     * Validates the page ID passed
     *
     * @since 1.0.0
     */
    private function validatePageID()
    {
        $validatedPageID       = filter_var( $this->pageID, FILTER_VALIDATE_INT );
        $this->validatedPageID = $validatedPageID;
    }

    /**
     * Public method init()
     *
     * This method is used to initialize our pre_get_posts action
     *
     * @since 1.0.0
     */
    public function init()
    {
        // Load the correct actions according to the value of $this->keepPageIntegrity
        add_action( 'pre_get_posts', [$this, 'preGetPosts'] );
    }

    /**
     * Protected method pageObject()
     *
     * Gets the queried object to use that as page object
     *
     * @since 1.0.0
     */
    protected function pageObject()
    {
        global $wp_the_query;
        return $wp_the_query->get_queried_object();
    }

    /**
     * Public method preGetPosts()
     *
     * This is our call back method for the pre_get_posts action.
     * 
     * The pre_get_posts action will only be used if the page integrity is
     * not an issue, which means that the page will be altered to work like a
     * normal archive page. Here you have the option to inject the page object as
     * first post through the_posts filter when $this->injectPageIntoLoop === true
     *
     * @since 1.0.0
     */
    public function preGetPosts( WP_Query $q )
    {
        // Make sure that we are on the main query and the desired page
        if (    is_admin() // Only run this on the front end
             || !$q->is_main_query() // Only target the main query
             || !is_page( $this->validatedPageID ) // Run this only on the page specified
        )
            return;

        // Remove the filter to avoid infinte loops
        remove_filter( current_filter(), [$this, __METHOD__] );

        // METHODS:
        $this->validatePageID();
        $this->pageObject();

        $queryArgs             = $this->args;

        // Set default arguments which cannot be changed 
        $queryArgs['pagename'] = NULL;

        // We have reached this point, lets do what we need to do
        foreach ( $queryArgs as $key=>$value ) 
            $q->set( 
                filter_var( $key, FILTER_SANITIZE_STRING ),
                $value // Let WP_Query handle the sanitation of the values accordingly
            );

        // Set $q->is_singular to 0 to get pagination to work
        $q->is_singular = false;

        // FILTERS:
        add_filter( 'the_posts',        [$this, 'addPageAsPost'],   PHP_INT_MAX );
        add_filter( 'template_include', [$this, 'templateInclude'], PHP_INT_MAX );  
    }

    /**
     * Public callback method hooked to 'the_posts' filter
     * This will inject the queried object into the array of posts
     * if $this->injectPageIntoLoop === true
     *
     * @since 1.0.0
     */
    public function addPageAsPost( $posts )
    {
        // Inject the page object as a post if $this->injectPageIntoLoop == true
        if ( true === $this->injectPageIntoLoop )
            return array_merge( [$this->pageObject()], $posts );

        return $posts;
    }

    /**
     * Public call back method templateInclude() for the template_include filter
     *
     * @since 1.0.0
     */
    public function templateInclude( $template )
    {
        // Remove the filter to avoid infinte loops
        remove_filter( current_filter(), [$this, __METHOD__] );

        // Get the page template saved in db
        $pageTemplate = get_post_meta( 
            $this->validatedPageID, 
            '_wp_page_template', 
            true 
        );

        // Make sure the template exists before we load it, but only if $template is not 'default'
        if ( 'default' !== $pageTemplate ) {
            $locateTemplate = locate_template( $pageTemplate );
            if ( $locateTemplate )
                return $template = $locateTemplate;
        }

        /**
         * If $template returned 'default', or the template is not located for some reason,
         * we need to get and load the template according to template hierarchy
         *
         * @uses get_page_template()
         */
        return $template = get_page_template();
    }
}

$init = new PreGeTPostsForPages(
    251, // Page ID
    false,
    [
        'posts_per_page' => 3,
        'post_type'      => 'post'
    ]
);
$init->init();

透過使用 my own pagination function,這樣可以很好地預覽頁面。

問題:

由於功能,我鬆散頁面完整性其他功能依賴於儲存在 $post 中的頁面物件。 $post 在迴圈之前設定為迴圈中的第一個後,$post 設定為迴圈後的最後一個迴圈,這是預期的。我需要的是將 $post 設定為當前頁面物件,即查詢物件。

此外,$wp_the_query->post$wp_query->post 儲存迴圈中的第一個帖子,而不是正常頁面上的查詢物件

我使用以下 (我的課外) 來檢查迴圈之前和之後的全域性變數

add_action( 'wp_head',   'printGlobals' );
add_action( 'wp_footer', 'printGlobals' );
function printGlobals()
{
    $global_test  = 'QUERIED OBJECT: ' . $GLOBALS['wp_the_query']->queried_object_id . '</br>';
    $global_test .= 'WP_THE_QUERY: ' . $GLOBALS['wp_the_query']->post->ID . '</br>';
    $global_test .= 'WP_QUERY: ' . $GLOBALS['wp_query']->post->ID . '</br>';
    $global_test .= 'POST: ' . $GLOBALS['post']->ID . '</br>';
    $global_test .= 'FOUND_POSTS: ' . $GLOBALS['wp_query']->found_posts . '</br>';
    $global_test .= 'MAX_NUM_PAGES: ' . $GLOBALS['wp_query']->max_num_pages . '</br>';

    ?><pre><?php var_dump( $global_test ); ?></pre><?php
}

在迴圈之前:

在迴圈之前,透過將 $injectPageIntoLoop 設定為 true 來部分解決問題,將頁面物件注入迴圈中的第一頁。如果您需要在所請求的帖子之前顯示頁面資訊,那麼這是非常有用的,但如果您不想要的話,您將被擰緊。

我可以透過直接駭客全域性變數在迴圈之前解決問題,我不太喜歡。我將以下方法鉤在我的 preGetPosts 方法中

public function wp()
{
    $page                          = get_post( $this->pageID );
    $GLOBALS['wp_the_query']->post = $page;
    $GLOBALS['wp_query']           = $GLOBALS['wp_the_query'];
    $GLOBALS['post']               = $page;
}

並在 preGetPosts 方法內

add_action( 'wp', [$this, 'wp'] );

從此,$wp_the_query->post$wp_query->post$post 都儲存頁面物件。

迴圈後

這是我的大問題,迴圈之後。透過 wp 鉤子和方法對全域性變數進行攻擊後,

  • $wp_the_query->post$wp_query->post 設定回迴圈中的第一個帖子,如預期

  • $post 設定為迴圈中的最後一個帖子。

我需要的是所有三個都被設定回查詢物件/當前頁面物件。

我嘗試將 wp 方法掛接到 loop_end 操作,這不行。將 wp 方法掛接到 get_sidebar 操作中,但是為時已晚。

add_action( 'get_sidebar', [$this, 'wp'] );

在模板迴圈後直接執行 printGlobals()確認為 $wp_the_query->post$wp_query->post 仍然設定為第一個帖子,$post 為最後一個帖子。

wp 方法之後,我可以在模板中的迴圈之後手動新增程式碼,但這個想法不是直接改變模板檔案,因為類應該可以在主題之間的外掛中傳輸。

有沒有正確的方法來解決這個問題,一個在真正的頁面和靜態首頁上執行 pre_get_posts,並且在迴圈之前和之後仍然保持 $wp_the_query->post$wp_query->post$post(將它們設定為被查詢物件) 的完整性。

EDIT

似乎有一些混亂,我需要什麼,為什麼我需要它

我需要的

我需要在模板中保留 $wp_the_query->post$wp_query->post$post 的值,而不管該值是查詢物件。在這個階段,使用我釋出的程式碼,這三個變數的值不會保留頁面物件,而是在迴圈中釋出帖子的物件。我希望這是很清楚的。

我已經發布了可以用來測試這些變數的程式碼

為什麼我需要它

我需要一種可靠的方式,透過 pre_get_posts 新增帖子到頁面模板和靜態前端頁面,而不會改變整頁功能。在這個階段,正如所討論的程式碼所示,由於 $post 擁有”wrong” 後期物件,因此在迴圈後會破壞我的導航特徵和相關頁面功能。

最重要的是,我不想直接改變頁面模板。我想要能夠向頁面模板新增帖子,而不會對模板進行任何修改

最佳解決方案

我終於得到它的工作,但不是在我的問題的程式碼。我完全廢棄了整個想法,重新開始向新的方向前進。

注意:

如果任何人有能力解決我的問題的問題,請隨時釋出答案。此外,如果您有任何其他解決方案,也可以隨時釋出答案。

工作類和解決方案:

我試圖在這裡做的是使用後期注入,而不是完全改變主查詢,並遇到上述所有問題,比如直接更改全域性變數,全域性值問題和重新分配頁面模板。

透過使用後期注入,我可以保持完整的完整性,所以 $wp_the_query->post$wp_query->post$posts$post 在整個模板中保持不變,它們只儲存當前頁面物件,如真正的頁面一樣。這樣,像麵包屑這樣的功能仍然認為當前頁面是真實的頁面,而不是某種存檔

我不得不稍微改變主要查詢 (透過過濾器和操作) 來調整分頁,但是我們會來。

後注射查詢

為了完成後期注入,我使用自定義查詢返回注入所需的帖子。我還使用自定義查詢的 $found_pages 屬性來調整主查詢的屬性,以便從主查詢獲取分頁。帖子透過 loop_end 動作注入主查詢。

為了使定製查詢在課外可訪問和可用,我介紹了一些動作。

  • 分頁鉤為了分頁功能:

    • pregetgostsforgages_before_loop_pagination

    • pregetgostsforgages_after_loop_pagination

  • 自定義計數器,用於計算迴圈中的帖子。這些動作可以用來根據帖子號來改變帖子在迴圈內的顯示方式

    • pregetgostsforgages_counter_before_template_part

    • pregetgostsforgages_counter_after_template_part

  • 一般鉤子訪問查詢物件和當前的 post 物件

    • pregetgostsforgages_current_post_and_object

這些鉤子為您提供了一個完整的 hands-off 體驗,因為您不需要更改頁面模板本身中的任何內容,這是我從一開始我的初衷。一個頁面可以完全從一個外掛或功能檔案改變,這使得這個非常動態

我也使用 get_template_part()載入一個模板部分,用於顯示帖子。今天的大多數主題都使用模板部分,這使得這在課堂上非常有用。如果您的主題使用 content.php,您可以簡單地將 content 傳遞給 $templatePart 來載入 content.php

如果您需要模板部件的後期格式支援,那麼很簡單,您仍然可以將 content 傳遞給 $templatePart,並將 $postFormatSupport 設定為 true,併為 video 的後期格式載入一個模板零件 content-video.php

主要查詢

透過相應的過濾器和操作對主查詢進行了以下更改

  • 為了分頁主要查詢:

    • 注射器查詢的 $found_posts 屬性值透過 found_posts 過濾器傳遞給主查詢物件的屬性值

    • 透過 pre_get_posts 將使用者傳遞引數 posts_per_page 的值設定為主查詢

    • $max_num_pages 使用 $found_postsposts_per_page 中的員額數量計算。因為 is_singular 在頁面上是正確的,它禁止設定 LIMIT 子句。簡單地將 is_singular 設定為 false 會導致一些問題,所以我決定透過 post_limits 過濾器設定 LIMIT 子句。我將 LIMIT 子句的 offset 設定為 0,以避免頁面上的 404 頁面

這樣做可以照顧分頁和從後期注入可能產生的任何問題

頁面物件

當前頁面物件可以透過使用頁面上的預設迴圈顯示為帖子,分離和注入帖子頂部。如果不需要,可以將 $removePageFromLoop 設定為 true,這樣可以隱藏頁面內容的顯示。

在這個階段,我使用 CSS 透過 loop_startloop_end 操作來隱藏頁面物件,因為我找不到另一種方法。這種方法的缺點是,如果隱藏頁面物件,任何掛鉤到主查詢中的 the_post 動作鉤子的內容也將被隱藏。

班上

PreGetPostsForPages 類可以改進,並且應該具有適當的名稱空間儘管您可以簡單地將其放在主題的函式檔案中,但最好將其放入自定義外掛中。

使用,修改和濫用,你認為合適。程式碼很好評論,所以應該很容易跟進和調整

class PreGetPostsForPages
{
    /**
     * @var string|int $pageID
     * @access protected     
     * @since 1.0.0
     */
    protected $pageID;

    /**
     * @var string $templatePart
     * @access protected     
     * @since 1.0.0
     */
    protected $templatePart;

    /**
     * @var bool $postFormatSupport
     * @access protected     
     * @since 1.0.0
     */
    protected $postFormatSupport;

    /**
     * @var bool $removePageFromLoop
     * @access protected     
     * @since 1.0.0
     */
    protected $removePageFromLoop;

    /**
     * @var array $args
     * @access protected     
     * @since 1.0.0
     */
    protected $args;

    /**
     * @var array $mergedArgs
     * @access protected     
     * @since 1.0.0
     */
    protected $mergedArgs = [];

    /**
     * @var NULL|stdClass $injectorQuery
     * @access protected     
     * @since 1.0.0
     */
    protected $injectorQuery = NULL;

    /**
     * @var int $validatedPageID
     * @access protected     
     * @since 1.0.0
     */
    protected $validatedPageID = 0;

    /** 
     * Constructor method
     *
     * @param string|int $pageID The ID of the page we would like to target
     * @param string $templatePart The template part which should be used to display posts
     * @param string $postFormatSupport Should get_template_part support post format specific template parts
     * @param bool $removePageFromLoop Should the page content be displayed or not
     * @param array $args An array of valid arguments compatible with WP_Query
     *
     * @since 1.0.0
     */      
    public function __construct( 
        $pageID             = NULL,
        $templatePart       = NULL,
        $postFormatSupport  = false,
        $removePageFromLoop = false,
        $args               = [] 
    ) {
        $this->pageID             = $pageID;
        $this->templatePart       = $templatePart;
        $this->postFormatSupport  = $postFormatSupport;
        $this->removePageFromLoop = $removePageFromLoop;
        $this->args               = $args;
    }

    /**
     * Public method init()
     *
     * The init method will be use to initialize our pre_get_posts action
     *
     * @since 1.0.0
     */
    public function init()
    {
        // Initialise our pre_get_posts action
        add_action( 'pre_get_posts', [$this, 'preGetPosts'] );
    }

    /**
     * Private method validatePageID()
     *
     * Validates the page ID passed
     *
     * @since 1.0.0
     */
    private function validatePageID()
    {
        $validatedPageID = filter_var( $this->pageID, FILTER_VALIDATE_INT );
        $this->validatedPageID = $validatedPageID;
    }

    /**
     * Private method mergedArgs()
     *
     * Merge the default args with the user passed args
     *
     * @since 1.0.0
     */
    private function mergedArgs()
    {
        // Set default arguments
        if ( get_query_var( 'paged' ) ) {
            $currentPage = get_query_var( 'paged' );
        } elseif ( get_query_var( 'page' ) ) {
            $currentPage = get_query_var( 'page' );
        } else {
            $currentPage = 1;
        }
        $default = [
            'suppress_filters'    => true,
            'ignore_sticky_posts' => 1,
            'paged'               => $currentPage,
            'posts_per_page'      => get_option( 'posts_per_page' ), // Set posts per page here to set the LIMIT clause etc
            'nopaging'            => false
        ];    
        $mergedArgs = wp_parse_args( (array) $this->args, $default );
        $this->mergedArgs = $mergedArgs;
    }

    /**
     * Public method preGetPosts()
     *
     * This is the callback method which will be hooked to the 
     * pre_get_posts action hook. This method will be used to alter
     * the main query on the page specified by ID.
     *
     * @param stdClass WP_Query The query object passed by reference
     * @since 1.0.0
     */
    public function preGetPosts( WP_Query $q )
    {
        if (    !is_admin() // Only target the front end
             && $q->is_main_query() // Only target the main query
             && $q->is_page( filter_var( $this->validatedPageID, FILTER_VALIDATE_INT ) ) // Only target our specified page
        ) {
            // Remove the pre_get_posts action to avoid unexpected issues
            remove_action( current_action(), [$this, __METHOD__] );

            // METHODS:
            // Initialize our method which will return the validated page ID
            $this->validatePageID();
            // Initiale our mergedArgs() method
            $this->mergedArgs();
            // Initiale our custom query method
            $this->injectorQuery();

            /**
             * We need to alter a couple of things here in order for this to work
             * - Set posts_per_page to the user set value in order for the query to
             *   to properly calculate the $max_num_pages property for pagination
             * - Set the $found_posts property of the main query to the $found_posts
             *   property of our custom query we will be using to inject posts
             * - Set the LIMIT clause to the SQL query. By default, on pages, `is_singular` 
             *   returns true on pages which removes the LIMIT clause from the SQL query.
             *   We need the LIMIT clause because an empty limit clause inhibits the calculation
             *   of the $max_num_pages property which we need for pagination
             */
            if (    $this->mergedArgs['posts_per_page'] 
                 && true !== $this->mergedArgs['nopaging']
            ) {
                $q->set( 'posts_per_page', $this->mergedArgs['posts_per_page'] );
            } elseif ( true === $this->mergedArgs['nopaging'] ) {
                $q->set( 'posts_per_page', -1 );
            }

            // FILTERS:
            add_filter( 'found_posts', [$this, 'foundPosts'], PHP_INT_MAX, 2 );
            add_filter( 'post_limits', [$this, 'postLimits']);

            // ACTIONS:
            /**
             * We can now add all our actions that we will be using to inject our custom
             * posts into the main query. We will not be altering the main query or the 
             * main query's $posts property as we would like to keep full integrity of the 
             * $post, $posts globals as well as $wp_query->post. For this reason we will use
             * post injection
             */     
            add_action( 'loop_start', [$this, 'loopStart'], 1 );
            add_action( 'loop_end',   [$this, 'loopEnd'],   1 );
        }    
    }    

    /**
     * Public method injectorQuery
     *
     * This will be the method which will handle our custom
     * query which will be used to 
     * - return the posts that should be injected into the main
     *   query according to the arguments passed
     * - alter the $found_posts property of the main query to make
     *   pagination work 
     *
     * @link https://codex.wordpress.org/Class_Reference/WP_Query
     * @since 1.0.0
     * @return stdClass $this->injectorQuery
     */
    public function injectorQuery()
    {
        //Define our custom query
        $injectorQuery = new WP_Query( $this->mergedArgs );

        // Update the thumbnail cache
        update_post_thumbnail_cache( $injectorQuery );

        $this->injectorQuery = $injectorQuery;

        return $this->injectorQuery;
    }

    /**
     * Public callback method foundPosts()
     * 
     * We need to set found_posts in the main query to the $found_posts
     * property of the custom query in order for the main query to correctly 
     * calculate $max_num_pages for pagination
     *
     * @param string $found_posts Passed by reference by the filter
     * @param stdClass WP_Query Sq The current query object passed by refence
     * @since 1.0.0
     * @return $found_posts
     */
    public function foundPosts( $found_posts, WP_Query $q )
    {
        if ( !$q->is_main_query() )
            return $found_posts;

        remove_filter( current_filter(), [$this, __METHOD__] );

        // Make sure that $this->injectorQuery actually have a value and is not NULL
        if (    $this->injectorQuery instanceof WP_Query 
             && 0 != $this->injectorQuery->found_posts
        )
            return $found_posts = $this->injectorQuery->found_posts;

        return $found_posts;
    }

    /**
     * Public callback method postLimits()
     *
     * We need to set the LIMIT clause as it it is removed on pages due to 
     * is_singular returning true. Witout the limit clause, $max_num_pages stays
     * set 0 which avoids pagination. 
     *
     * We will also leave the offset part of the LIMIT cluase to 0 to avoid paged
     * pages returning 404's
     *
     * @param string $limits Passed by reference in the filter
     * @since 1.0.0
     * @return $limits
     */
    public function postLimits( $limits )
    {
        $posts_per_page = (int) $this->mergedArgs['posts_per_page'];
        if (    $posts_per_page
             && -1   !=  $posts_per_page // Make sure that posts_per_page is not set to return all posts
             && true !== $this->mergedArgs['nopaging'] // Make sure that nopaging is not set to true
        ) {
            $limits = "LIMIT 0, $posts_per_page"; // Leave offset at 0 to avoid 404 on paged pages
        }

        return $limits;
    }

    /**
     * Public callback method loopStart()
     *
     * Callback function which will be hooked to the loop_start action hook
     *
     * @param stdClass WP_Query $q Query object passed by reference
     * @since 1.0.0
     */
    public function loopStart( WP_Query $q )
    {
        /**
         * Although we run this action inside our preGetPosts methods and
         * and inside a main query check, we need to redo the check here aswell
         * because failing to do so sets our div in the custom query output as well
         */

        if ( !$q->is_main_query() )
            return;

        /** 
         * Add inline style to hide the page content from the loop
         * whenever $removePageFromLoop is set to true. You can
         * alternatively alter the page template in a child theme by removing
         * everything inside the loop, but keeping the loop
         * Example of how your loop should look like:
         *     while ( have_posts() ) {
         *     the_post();
         *         // Add nothing here
         *     }
         */
        if ( true === $this->removePageFromLoop )
            echo '<div style="display:none">';
    }   

    /**
     * Public callback method loopEnd()
     *
     * Callback function which will be hooked to the loop_end action hook
     *
     * @param stdClass WP_Query $q Query object passed by reference
     * @since 1.0.0
     */
    public function loopEnd( WP_Query $q )
    {  
        /**
         * Although we run this action inside our preGetPosts methods and
         * and inside a main query check, we need to redo the check here as well
         * because failing to do so sets our custom query into an infinite loop
         */
        if ( !$q->is_main_query() )
            return;

        // See the note in the loopStart method  
        if ( true === $this->removePageFromLoop )
            echo '</div>';

        //Make sure that $this->injectorQuery actually have a value and is not NULL
        if ( !$this->injectorQuery instanceof WP_Query )
            return; 

        // Setup a counter as wee need to run the custom query only once    
        static $count = 0;    

        /**
         * Only run the custom query on the first run of the loop. Any consecutive
         * runs (like if the user runs the loop again), the custom posts won't show.
         */
        if ( 0 === (int) $count ) {      
            // We will now add our custom posts on loop_end
            $this->injectorQuery->rewind_posts();

            // Create our loop
            if ( $this->injectorQuery->have_posts() ) {

                /**
                 * Fires before the loop to add pagination.
                 *
                 * @since 1.0.0
                 *
                 * @param stdClass $this->injectorQuery Current object (passed by reference).
                 */
                do_action( 'pregetgostsforgages_before_loop_pagination', $this->injectorQuery );


                // Add a static counter for those who need it
                static $counter = 0;

                while ( $this->injectorQuery->have_posts() ) {
                    $this->injectorQuery->the_post(); 

                    /**
                     * Fires before get_template_part.
                     *
                     * @since 1.0.0
                     *
                     * @param int $counter (passed by reference).
                     */
                    do_action( 'pregetgostsforgages_counter_before_template_part', $counter );

                    /**
                     * Fires before get_template_part.
                     *
                     * @since 1.0.0
                     *
                     * @param stdClass $this->injectorQuery-post Current post object (passed by reference).
                     * @param stdClass $this->injectorQuery Current object (passed by reference).
                     */
                    do_action( 'pregetgostsforgages_current_post_and_object', $this->injectorQuery->post, $this->injectorQuery );

                    /** 
                     * Load our custom template part as set by the user
                     * 
                     * We will also add template support for post formats. If $this->postFormatSupport
                     * is set to true, get_post_format() will be automatically added in get_template part
                     *
                     * If you have a template called content-video.php, you only need to pass 'content'
                     * to $template part and then set $this->postFormatSupport to true in order to load
                     * content-video.php for video post format posts
                     */
                    $part = '';
                    if ( true === $this->postFormatSupport )
                        $part = get_post_format( $this->injectorQuery->post->ID ); 

                    get_template_part( 
                        filter_var( $this->templatePart, FILTER_SANITIZE_STRING ), 
                        $part
                    );

                    /**
                     * Fires after get_template_part.
                     *
                     * @since 1.0.0
                     *
                     * @param int $counter (passed by reference).
                     */
                    do_action( 'pregetgostsforgages_counter_after_template_part', $counter );

                    $counter++; //Update the counter
                }

                wp_reset_postdata();

                /**
                 * Fires after the loop to add pagination.
                 *
                 * @since 1.0.0
                 *
                 * @param stdClass $this->injectorQuery Current object (passed by reference).
                 */
                do_action( 'pregetgostsforgages_after_loop_pagination', $this->injectorQuery );
            }
        }

        // Update our static counter
        $count++;       
    }
}  

USAGE

您現在可以啟動課程 (也可以在您的外掛或函式檔案中) 按照以下步驟定位頁面,其中我們將從 post 帖子型別顯示每頁 2 個帖子

$query = new PreGetPostsForPages(
    251,       // Page ID we will target
    'content', //Template part which will be used to display posts, name should be without .php extension 
    true,      // Should get_template_part support post formats
    false,     // Should the page object be excluded from the loop
    [          // Array of valid arguments that will be passed to WP_Query/pre_get_posts
        'post_type'      => 'post', 
        'posts_per_page' => 2
    ] 
);
$query->init(); 

新增分類和自定義

正如我所說,為了新增分頁或自定義樣式,進樣器查詢中有一些操作。這裡我用 my own pagination function from the linked answer 迴圈後新增了分頁。另外,使用內建的計數器,我新增了一個 div 來顯示我的帖子在兩個列。

這是我使用的動作

add_action( 'pregetgostsforgages_counter_before_template_part', function ( $counter )
{
    $class = $counter%2  ? ' right' : ' left';
    echo '<div class="entry-column' . $class . '">';
});

add_action( 'pregetgostsforgages_counter_after_template_part', function ( $counter )
{
    echo '</div>';
});

add_action( 'pregetgostsforgages_after_loop_pagination', function ( WP_Query $q )
{
    paginated_numbers();    
});

注意,分頁是由主查詢設定的,而不是進樣器查詢,所以 build-in 的功能如 the_posts_pagination()也應該有效。

這是最終的結果

靜態頁面

一切都按照預期在靜態前端頁面和我的分頁功能一起工作,而無需做任何修改

CONCLUSION

這似乎是一個非常多的間接費用,可能是,但是,該公司的優勢超過了公司的大時間

大哥

  • 您不需要以任何方式更改特定頁面的頁面模板。這使得一切都是動態的,並且可以容易地在主題之間傳遞,而無需對程式碼進行任何修改,如果一切都在外掛中完成。

  • 您最多隻需要在主題中建立一個 content.php 模板部分,如果您的主題還沒有

  • 對主查詢工作的任何分頁都可以在頁面上進行,而無需任何型別的更改或任何額外的查詢被傳遞給函式。

有更多的親我現在不能想到,但這些都是重要的

參考文獻

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