Frage

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?

War es hilfreich?

Lösung

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?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit wordpress.stackexchange
scroll top