Включить липкие записи в число записей на странице для пользовательского запроса


Эта ссылка решает проблему, но она предназначена только для основного запроса. Что делать, если вы используете пользовательский запрос? Как вы можете изменить ответ ниже:

add_action('pre_get_posts', 'ad_custom_query');
function ad_custom_query($query) {

    if ($query->is_main_query() && is_home()) { //how can we for specific custom query?

        // set the number of posts per page
        $posts_per_page = 12;
        // get sticky posts array
        $sticky_posts = get_option( 'sticky_posts' );

        // if we have any sticky posts and we are at the first page
        if (is_array($sticky_posts) && !$query->is_paged()) {

            // counnt the number of sticky posts
            $sticky_count = count($sticky_posts);

            // and if the number of sticky posts is less than
            // the number we want to set:
            if ($sticky_count < $posts_per_page) {
                $query->set('posts_per_page', $posts_per_page - $sticky_count);

            // if the number of sticky posts is greater than or equal
            // the number of pages we want to set:
            } else {
                $query->set('posts_per_page', 1);
            }

        // fallback in case we have no sticky posts
        // and we are not on the first page
        } else {
            $query->set('posts_per_page', $posts_per_page);
        }
    }
}
Author: Community, 2015-08-02

2 answers

Я думаю, мы можем попробовать следующее: ( ПРИМЕЧАНИЕ: Это непроверено, но теоретически должно работать, но помните, что оно непроверено и может быть ошибочным)

add_action('pre_get_posts', 'ad_custom_query');
function ad_custom_query($query) {
    // No other checks should be necessary
    if ( $query->get( 'custom_query' ) === 1 ) ) {
        // set the number of posts per page
        $posts_per_page = 12;
        // get sticky posts array
        $sticky_posts = get_option( 'sticky_posts' );

        // if we have any sticky posts and we are at the first page
        if (is_array($sticky_posts) && !$query->is_paged()) {

            // counnt the number of sticky posts
            $sticky_count = count($sticky_posts);

            // and if the number of sticky posts is less than
            // the number we want to set:
            if ($sticky_count < $posts_per_page) {
            $query->set('posts_per_page', $posts_per_page - $sticky_count);

            // if the number of sticky posts is greater than or equal
            // the number of pages we want to set:
            } else {
                $query->set('posts_per_page', 1);
            }

        // fallback in case we have no sticky posts
        // and we are not on the first page
        } else {
            $query->set('posts_per_page', $posts_per_page);
        }
    }
}

Теперь вы можете просто выполнить следующий пользовательский запрос

$args = [
    'custom_query' => 1, // Note, this has to be an integer, '1' will not work
    'paged' = > $paged
// I would just add all the other parameters in the pre_get_posts action
];
$q = new WP_Query( $args );

НЕСКОЛЬКО ПРИМЕЧАНИЙ:

  • Поскольку мы будем ориентироваться только на запросы, для которых новый параметр custom_query установлен в 1, нам не понадобятся проверки, такие как !is_admin() или is_main_query()

  • Потому что мы выполняем действие pre_get_posts на в нашем пользовательском запросе я бы просто установил параметры custom_query и paged в аргументах запроса. Любые другие параметры я бы просто добавил в действие pre_get_posts.

  • Если вам нужно выполнить второй запрос с другим параметром и/или значениями, вы можете просто установить custom_query в 2, а затем просто проверить, имеет ли $query->get( 'custom_query' ) значение 2, например if ( $query->get( 'custom_query' ) === 2 ) {

  • Я только что скопировал ваш код и добавил новую проверку параметров, я не работал с вашим кодом и не менял его что угодно

 1
Author: Pieter Goosen, 2015-08-02 08:54:37

Вместо создания функции я просто отредактировал цикл с помощью пользовательского запроса. Мой пример - показать только один пост.

Я просто использовал оператор if, если один или несколько липких просто показывают первый липкий.

<?php
$sticky_posts = get_option( 'sticky_posts' );
$sticky_count = count($sticky_posts);

if($sticky_count >= 1) {
    $loop = new WP_Query('p=' . $sticky_posts[0]); //show only first sticky
} else {
    $loop = new WP_Query( array( 'post_type' => 'post', 'category__not_in' => 'featured', 'posts_per_page' => 1 ) ); //if none show just the first non-sticky post
}

while ( $loop->have_posts() ) : $loop->the_post();
?>
 1
Author: Zakir Hossen Sujon, 2015-08-02 09:18:23