I'm working on a site where the client wants only the linked titles of all posts in a particular category on one page. That is, the query does not pick up the smaller number of posts that is defined in Settings from that one particular template.

I could do this if I by-pass the loop entirely, but is it possible within the normal loop?


The best way to do this is to use the pre_get_posts filter, which changes the main query. That way you're not running the default query plus a custom one on top of it. You'll have to determine the "if" conditions to only run on the query you want to affect:

function wpse_366882_get_all_posts($query) {
    // This will run for all main queries that are not in wp-admin.
    // You may want "is_archive()", "is_page('slug')" or some other condition.
    if ( ! is_admin() && $query->is_main_query() ) {
    // Setting to -1 shows all.
        $query->set( 'posts_per_page', -1 );
add_action( 'pre_get_posts', 'wpse_366882_get_all_posts' );

You can place this code in a custom plugin, or in a custom theme or child theme's functions.php file.

  • So, as long as I have a unique name for the function and only call it on that one template, it will only affect the query for template? – Nora McDougall-Collins May 17 '20 at 23:13
  • 1
    You don't call the function on a template. The add_action() calls it at the pre_get_posts hook, which fires on every page, even in wp-admin. That's why you need the correct conditional to tell WP "Don't fire this on admin pages, and only fire on the main query" - that's the part you will need to fill in to be more specific and make it only affect the query you want to affect. – WebElaine May 18 '20 at 13:42
  • Thanks for the clarification. It seems that it would then affect all templates, not just one. I may need to just set up a new query object.that includes all the posts in that category. – Nora McDougall-Collins May 18 '20 at 14:50
  • 1
    You just need to set up the "if" condition correctly so it only applies to the template you want it to. If you run a custom query instead, you'll actually be running 2 separate queries on the page which takes up server resources for no output. – WebElaine May 18 '20 at 17:36
  • I see now that I understood "the query you want to affect" in a more general way than you meant. – Nora McDougall-Collins May 19 '20 at 18:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.