Combined Search for Author & Custom Post Type

送分小仙女□ 提交于 2019-12-25 02:05:53

问题


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:


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;
}


来源:https://stackoverflow.com/questions/21637517/combined-search-for-author-custom-post-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!