Unlimited posts_per_page for a custom post type only

11,045

Do a check in your pre get posts with the is_post_type_archive function for the post type.

You will want to check if the query is not admin to avoid affecting the admin area, as well as checking if the query is the main query.

function get_all_vehicle_posts( $query ) {
    if( !is_admin() && $query->is_main_query() && is_post_type_archive( 'vehicle' ) ) {
        $query->set( 'posts_per_page', '-1' );
    }
}
add_action( 'pre_get_posts', 'get_all_vehicle_posts' );

http://codex.wordpress.org/Function_Reference/is_admin

http://codex.wordpress.org/Function_Reference/is_main_query

http://codex.wordpress.org/Function_Reference/is_post_type_archive

Share:
11,045
gpcola
Author by

gpcola

PHP, Javascript and all things 'web' developer.

Updated on September 08, 2022

Comments

  • gpcola
    gpcola over 1 year

    I need to show all existing posts in the archive loop for a custom post type of 'vehicle'.

    This is what I have so far:

    function get_all_vehicle_posts( $query ) {
        $query->set( 'posts_per_page', '-1' );
    }
    add_action( 'pre_get_posts', 'get_all_vehicle_posts' );
    

    And I see the unlimited posts I wanted. However I need to limit this change to my custom post type.

    I tried:

        if ( 'vehicle' == $query->post_type ) {
            $query->set( 'posts_per_page', '-1' );
        }
    

    but that doesn't seem to work. I guess we don't know the post type before the query is run unless it's a specific argument for the query?

    How can I limit this function to a particular post type?