Include both default and Custom Post Type in query modified inside pre_get_posts

I want to include custom post type in the author arhive page. I tried the method discussed in this post:

Including post_type = ‘wiki’ in author archives

Read More
add_action( 'pre_get_posts', 'custom_post_author_archive' );
function custom_post_author_archive( &$query )
{
    if ( $query->is_author )
    {
        $query->set( 'post_type', 'custom_name' );
        remove_action( 'pre_get_posts', 'custom_post_author_archive' ); // run once!
    }
}

But by this method, only the custom_name posts are queried. I want to query both the custom_name posts and the normal posts.

What changes will I have to make?

Related posts

2 comments

  1. As Kaiser mentioned, the post_type parameter can accept an array of post types. Updating the function to use is_main_query() to limit the filter to only the “main” query, the code would look like:

    add_action( 'pre_get_posts', 'custom_post_author_archive' );
    function custom_post_author_archive( $query )
    {
        if ( is_main_query() && is_author() )
        {
            set_query_var( 'post_type', array('post','custom_post') );
        }
    }
    
  2. Simply said, the $query argument inside pre_get_posts refers to the WP_Query class/object as you can see in core.

    do_action_ref_array( 'pre_get_posts', array( &$this ) );
    

    That means that any callback/action attached to the hook can do exactly the same thing as new WP_Query( [ etc. ] ); could do. Therefore you can use an array of post types as well.

Comments are closed.