1

I have a custom post type archive where WP_Query is used to retrieve the posts. I want to disable pagination and show all posts on this archive, but the following query is not working:

$args = array(
    'post_type' => array(
        'cpt_sports',
    ),
    'posts_per_page' => -1,
    'orderby' => 'menu_order',
    'order' => 'desc',
    'max_num_pages' => 1
);

$all_sports = new WP_Query($args);

What am I doing wrong here?

6

WP_Query is for secondary loops. That is to say that it's completely independent from the page's default $wp_query. I suspect that it's not working because you aren't referencing your new WP_Query object on the loop. To do that, you'd do this:

if( $all_sports->have_posts() ) : while( $all_sports->have_posts() ) : $all_sports->the_post();
    // do stuff
endwhile; endif;

HOWEVER, you shouldn't do that!

Instead, this is a perfect use of the pre_get_posts action. That action can be used to modify the default query on any page without any changes to the page template. Seeing that you're simply wanting to modify the default custom post type archive query, that's what you want. Here's some untested code that should probably do the trick:

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

    if( is_post_type_archive( 'cpt_sports' ) && !is_admin() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', -1 );
        $query->set( 'orderby', 'menu_order' );
    }

}

All the other arguments you give to WP_Query are defaults of a custom post type archive page query so you don't need to modify them.

  • you can add priority 11 to use it in a child theme – chris Sep 5 '15 at 22:45

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.