Combined Search for Author & Custom Post Type

2019-08-25 10:29发布

I have searched questions similar to mine but with no luck finding the answer I need.

I have Authors and I have Custom Post Types (CPT). My search results already display all CPT's -- but, additionally, I need something more specific than that. I need my search function to allow combined queries for a specific Author and specific CPT. For example, all Blogs by Albert Einstein.

This url "/?s=%20&author_name=alberteinstein" returns all posts across CPT's by Albert Einstein.

But if I add "&post_type=blogs" for the full url to filter for the CPT like this:

"/?s=%20&author_name=alberteinstein&post_type=blogs"

it does not filter for just Blogs -- it still returns all CPT's by the Author, same as above.

I need to be able to query for an Author and specific CPT.

This has been driving me crazy for weeks. Any help would be greatly appreciated.

1条回答
相关推荐>>
2楼-- · 2019-08-25 10:54

This may help (as worded on the WordPress Codex post types page). Basically, it may be that your custom post type (CPT) isn't registered for archive queries although it is legitimately registered for use as a CPT.

Registering a custom post type does not mean it gets added to the main query automatically. If you want your custom post type posts to show up on standard archives or include them on your home page mixed up with other post types, use the pre_get_posts action hook.

// Show posts of 'post', 'page' and 'movie' post types on home page
add_action( 'pre_get_posts', 'add_my_post_types_to_query' );

function add_my_post_types_to_query( $query ) {
    if ( is_home() && $query->is_main_query() )
        $query->set( 'post_type', array( 'post', 'page', 'movie' ) );
    return $query;
}
查看更多
登录 后发表回答