下面的解决方案将返回与查询的术语名称关联的帖子or 在文章标题、摘录或内容中使用术语名称的文章。
请注意,我们在搜索中使用的是人类可读的术语名称,而不是术语slug,因为slug可以连字符,因此不适合用于搜索。
首先,将分类术语的名称添加到搜索查询中,并连接过滤器以更改搜索SQL:
/**
* Adds taxonomy term name to search query and wires up posts_search
* filter to change the search SQL.
*
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
add_action( \'pre_get_posts\', \'wpse_add_term_search_to_term_archive\' );
function wpse_add_term_search_to_term_archive( $query ) {
// Bail if this is the admin area or not the main query.
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
// Set the taxonomy associated with our term. Customize as needed.
$taxonomy_slug = \'genre\';
// Get the term being used.
$term_slug = get_query_var( $taxonomy_slug );
if ( is_tax( $taxonomy_slug ) && $term_slug ) {
// We have the term slug, but we need the human readable name. This
// will be available in the term object.
$term_object = get_term_by( \'slug\', $term_slug, $taxonomy_slug );
// Bail if we can\'t get the term object.
if ( ! $term_object ) {
return;
}
// Sets this query as a search and uses the current term for our search.
$query->set( \'s\' , $term_object->name );
// Wire up a filter that will alter the search SQL so that the term archive
// will include search results matching the term name *OR* posts assigned to
// the term being queried.
add_filter( \'posts_search\', \'wpse_tax_term_posts_search\', 10, 2 );
}
}
然后,修改搜索SQL,以便
either 税务查询
or 将返回搜索查询:
/**
* Change the search SQL so that results in the tax query OR
* the search query will be returned.
*
* @param string $search Search SQL for WHERE clause.
* @param WP_Query $wp_query The current WP_Query object.
*/
function wpse_tax_term_posts_search( $search, $wp_query ) {
// Replaces the first occurrence of " AND" with " OR" so that results in the
// tax query OR the search query will be returned.
return preg_replace( \'/^\\s(AND)/\', \' OR\', $search );
}