Использование pre_get_posts на настоящих страницах и статических первых страницах


19

Я провел довольно обширное исследование о том, как использовать pre_get_postsна настоящих страницах и статических титульных страницах, и кажется, что нет никакого метода защиты от дурака.

Лучший вариант, который я нашел на сегодняшний день, был из сообщения, написанного @birgire в 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();

Это работает хорошо и страница, как и ожидалось, используя мою собственную функцию нумерации страниц .

ПРОБЛЕМЫ:

Из-за этой функции я теряю целостность страницы, в которую входят другие функции, зависящие от объекта страницы, хранящегося в $post. $postbefore цикл установлен на первое сообщение в цикле и $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
}

ДО ПЕТЛИ:

Перед циклом проблема частично решается установкой значения $injectPageIntoLooptrue, которое вставляет объект страницы как первую страницу в цикл. Это очень полезно, если вам нужно показать информацию о странице перед запрошенными постами, но если вы этого не хотите, вы облажались.

Я могу решить проблему до начала цикла, напрямую взломав глобалы, что мне не очень нравится. Я подключаю следующий метод wpвнутрь моего 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()непосредственно после цикла в шаблоне подтверждает, что as $wp_the_query->postи $wp_query->postвсе еще установлены для первого и $postпоследнего сообщения.

Я могу вручную добавить код внутри wpметода после цикла внутри шаблона, но идея не в том, чтобы изменять файлы шаблона напрямую, поскольку класс должен передаваться в плагине между темами.

Есть ли надлежащим образом решить эту проблему , когда один прогон pre_get_postsна реальной странице и статической первой страницы и до сих пор сохранить целостность $wp_the_query->post, $wp_query->postи $post( имея те , которые в запрашиваемом объекта ) до и после цикла.

РЕДАКТИРОВАТЬ

Кажется, есть путаница в том, что мне нужно и зачем мне это нужно

Что мне нужно

Мне нужно , чтобы сохранить значения $wp_the_query->post, $wp_query->postи $postпо шаблону , независимо, и это значение должно быть запрашиваемый объект. На этом этапе, с кодом, который я разместил, значения этих трех переменных не содержат объект страницы, а скорее размещают объекты сообщений в цикле. Я надеюсь, что это достаточно ясно.

Я разместил код, который вы можете использовать для проверки этих переменных

Зачем мне это нужно

Мне нужен надежный способ добавления сообщений через pre_get_postsшаблоны страниц и статические титульные страницы без изменения полной функциональности страницы. На данном этапе, поскольку рассматриваемый код стоит, он нарушает мою функциональность хлебных крошек и связанную страницу после цикла, из-за $postкоторого содержится «неправильный» объект post.

Больше всего я не хочу изменять шаблоны страниц напрямую. Я хочу , чтобы иметь возможность добавлять сообщения в шаблон страницы без ЛЮБЫХ изменений в шаблон


Что вы пытаетесь сделать, ваши цели или функциональные требования? Ты нигде не утверждаешь, насколько я могу судить.
adelval

Ответы:


13

Я, наконец, получил его работать, но не с кодом в моем вопросе. Я полностью отказался от всей этой идеи и возобновил движение в новом направлении.

НОТА:

Если кто-нибудь когда-нибудь сможет разобраться с вопросами в моем вопросе, не стесняйтесь отправить ответ. Кроме того, если у вас есть какие-либо другие решения, не стесняйтесь опубликовать ответ.

ПЕРЕРАБОТАННЫЙ КЛАСС И РЕШЕНИЕ:

То, что я пытался сделать здесь, это использовать постинжекцию, а не полностью изменять основной запрос и зацикливаться на всех вышеперечисленных проблемах, включая (а) прямое изменение глобальных переменных, (б) столкновение с проблемой глобальной ценности и (в) переназначение шаблонов страниц.

При использовании после инъекции я могу сохранить полную целостность поста, поэтому $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

  • Общий хук для доступа к объекту запроса и текущему объекту публикации

    • pregetgostsforgages_current_post_and_object

Эти хуки дают вам полный опыт, так как вам не нужно ничего менять в самом шаблоне страницы, что было моим первоначальным намерением с самого начала. Страница может быть полностью изменена из плагина или файла функции, что делает это решение очень динамичным.

Я также использовал get_template_part()для того, чтобы загрузить часть шаблона, которая будет использоваться для отображения сообщений. Большинство тем сегодня используют части шаблона, что делает это очень полезным в классе. Если ваша тема использование content.php, вы можете просто передать contentв $templatePartнагрузку content.php.

Если вам нужна поддержка формата поста для частей шаблона, это просто - вы можете просто перейти contentк $templatePartи установить $postFormatSupportна true. В результате часть шаблона content-video.phpбудет загружена для сообщения с форматом сообщения video.

ОСНОВНОЙ ВОПРОС

Следующие изменения были внесены в основной запрос с помощью соответствующих фильтров и действий:

  • Чтобы разбить основной запрос на страницы:

    • Значение $found_postsсвойства запроса инжектора передается значению основного объекта запроса через found_postsфильтр.

    • Значение параметра, передаваемого пользователем posts_per_page, устанавливается через основной запрос pre_get_posts.

    • $max_num_pagesрассчитывается с использованием количества постов в $found_posts и posts_per_page. Поскольку is_singularэто верно для страниц, оно запрещает установку LIMITпредложения. Просто установка is_singularв false привела к нескольким проблемам, поэтому я решил установить LIMITпредложение через post_limitsфильтр. Я держал offsetв LIMITнаборе положение , чтобы 0избежать 404 на страницах с пагинацией включена.

Это заботится о нумерации страниц и любой проблеме, которая может возникнуть после пост-инъекции.

ОБЪЕКТ СТРАНИЦЫ

Текущий объект страницы доступен для отображения в виде сообщения с помощью цикла по умолчанию на странице, отдельно и поверх добавленных сообщений. Если вам это не нужно, вы можете просто установить $removePageFromLoopзначение true, и это будет скрывать содержимое страницы от отображения.

На данном этапе, я использую CSS , чтобы скрыть объект страницы через loop_startи loop_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++;       
    }
}  

ИСПОЛЬЗОВАНИЕ

Теперь вы можете инициировать класс ( также в вашем плагине или файле функций ), как показано ниже, чтобы настроить таргетинг на страницу с идентификатором 251, на котором мы будем показывать 2 поста на странице от postтипа поста.

$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(); 

ДОБАВЛЕНИЕ СТРАНИЦЫ И ТАМОЖЕННОГО СТИЛИРОВАНИЯ

Как я упоминал ранее, в запросе инжектора есть несколько действий для добавления нумерации страниц и / или пользовательских стилей.

В следующем примере я добавил разбиение на страницы после цикла, используя мою собственную функцию разбиения на страницы из связанного ответа . Кроме того, используя свой пользовательский счетчик, я добавил <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();    
});

Обратите внимание, что разбиение на страницы задается основным запросом, а не запросом инжектора, поэтому встроенные функции, такие как, the_posts_pagination()также должны работать.

Это конечный результат

введите описание изображения здесь

СТАТИЧЕСКИЕ ПЕРЕДНИЕ СТРАНИЦЫ

На статических титульных страницах все работает, как и ожидалось, вместе с моей функцией нумерации страниц, не требуя каких-либо дополнительных изменений

ВЫВОД

Это может показаться большим накладным расходом, и это может быть так, но профессионал перевешивает большое время мошенника.

BIG PRO'S

  • Вам не нужно каким-либо образом изменять шаблон страницы для конкретной страницы. Это делает все динамичным и может быть легко перенесено между темами без каких-либо изменений в коде, если все сделано в плагине.

  • Самое большее, вам нужно создать только content.phpчасть шаблона в вашей теме, если у вашей темы ее еще нет.

  • Любая нумерация страниц, которая работает с основным запросом, будет работать на странице без каких-либо изменений или каких-либо дополнительных действий из запроса, передаваемого в функцию.

Есть больше профессионалов, о которых я не могу думать сейчас, но это важные.


Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.