我找到了一个解决方案,允许我在搜索标题和内容的同时按标签和类别搜索帖子。这正是我想要的。
信用证:https://rfmeier.net/include-category-and-post-tag-names-in-the-wordpress-search/
add_filter( \'posts_join\', \'search_join\', 10, 2 );
/**
* Joins the terms, term_relationship, and term_taxonomy tables.
*
* @global $wpdb
*
* @param string $join The sql JOIN clause.
* @param object $query The current WP_Query instance.
*
* @return string $join
*/
function search_join( $join, $query ) {
global $wpdb;
if ( is_main_query() && is_search() ) {
$join .= "
LEFT JOIN
(
{$wpdb->term_relationships}
INNER JOIN
{$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_taxonomy_id = {$wpdb->term_relationships}.term_taxonomy_id
INNER JOIN
{$wpdb->terms} ON {$wpdb->terms}.term_id = {$wpdb->term_taxonomy}.term_id
)
ON {$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id ";
}
return $join;
}
add_filter( \'posts_where\', \'custom_posts_where\', 10, 2 );
/**
* Callback for WordPress \'posts_where\' filter.
*
* Modify the where clause to include searches against a WordPress taxonomy.
*
* @global $wpdb
*
* @param string $where The where clause.
* @param WP_Query $query The current WP_Query.
*
* @return string The where clause.
*/
function custom_posts_where( $where, $query ) {
global $wpdb;
if ( is_main_query() && is_search() ) {
// get additional where clause for the user
$user_where = custom_get_user_posts_where();
$where .= " OR (
{$wpdb->term_taxonomy}.taxonomy IN( \'category\', \'post_tag\' )
AND
{$wpdb->terms}.name LIKE \'%" . esc_sql( get_query_var( \'s\' ) ) . "%\'
{$user_where}
)";
}
return $where;
}
function custom_get_user_posts_where() {
global $wpdb;
$user_id = get_current_user_id();
$sql = \'\';
$status = array( "\'publish\'" );
if ( $user_id ) {
$status[] = "\'private\'";
$sql .= " AND {$wpdb->posts}.post_author = {$user_id}";
}
$sql .= " AND {$wpdb->posts}.post_status IN( " . implode( \',\', $status ) . " ) ";
return $sql;
}
add_filter( \'posts_groupby\', \'custom_posts_groupby\', 10, 2 );
/**
* Callback for WordPress \'posts_groupby\' filter.
*
* Set the GROUP BY clause to post IDs.
*
* @global $wpdb
*
* @param string $groupby The GROUPBY caluse.
* @param WP_Query $query The current WP_Query object.
*
* @return string The GROUPBY clause.
*/
function custom_posts_groupby( $groupby, $query ) {
global $wpdb;
if ( is_main_query() && is_search() ) {
$groupby = "{$wpdb->posts}.ID";
}
return $groupby;
}