Query Nopaging action not having effect

I’ve got a custom loop function in my child theme, in the templates.php file to loop through specific post types (‘listings’) and then put it into an array to use into a part of my template.

Here’s an example of the code

public function loop()
{

    global $wp_query;
    $featured = $regular = array();
    foreach ($wp_query->posts as $count => $post)
        if (has_term('featured', 'listings_tag', $post->ID))
            $featured[] = $post;
        else
            $regular[] = $post;
    $posts = array_merge($regular, $featured);
    $posts = array_reverse($posts);
    

    include('templates/loop.php');

}

So this is great, however, it paginates after every 11 posts.
Instead I would like it to display everything instead.

I tried by adding a custom action in my functions.php, making use of the ‘pre_get_posts’ hook. However it doesn’t have any effect on my code.

function show_all($query){
    if (is_post_type_archive('listings') && $query->is_main_query()) {
        $query->set('nopaging', True);
    }
}

add_action('pre_get_posts', 'show_all');

Any suggestions?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

nopaging does not fetch all posts, it just tells WordPress not to bother figuring out stuff like how many pages there are.

What you actually wanted was not to disable pagination, that’s just a solution to your problem that you asked about. You should ask about your problem instead, aka how to show all posts at once.

Showing all posts at once can be dangerous, so instead, set a limit that’s very high, e.g:

$query->set('posts_per_page', 500 );

Anything more than 500 posts will probably cause problems, or be extremely slow, as well as being extremely long winded. The idea being that you specify a number you never expect to reach. That way you know for a fact that the worst case scenario can’t happen. Why trust that there won’t be a broken plugin or a client who does something by accident when you can know for a fact the page won’t break?


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x