Unlimited posts_per_page for a custom post type on

2019-08-15 01:38发布

问题:

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?

回答1:

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



回答2:

The post type has to be set as a query parameter

$args = array(
    'post_type' => 'vehicle'
);

So in your function add the post type, otherwise you are only querying the standard post objects.



标签: wordpress