我想修改搜索,所以如果说我有一个名为“作者”的分类,并在帖子中添加“Ian Rankin”一词,如果我搜索“Ian Rankin”,我希望该帖子出现。我想目前它只搜索标题和内容。 如何进行搜索?
答案 0 :(得分:12)
您可以使用过滤器挂钩更改搜索查询以加入分类表。
e.g。还搜索“作者”分类法
首先加入分类表
function tax_search_join( $join )
{
global $wpdb;
if( is_search() )
{
$join .= "
INNER JOIN
{$wpdb->term_relationships} ON {$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id
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
";
}
return $join;
}
add_filter('posts_join', 'tax_search_join');
然后在分类标准“作者”
中找到搜索词function tax_search_where( $where )
{
global $wpdb;
if( is_search() )
{
// add the search term to the query
$where .= " OR
(
{$wpdb->term_taxonomy}.taxonomy LIKE 'author'
AND
{$wpdb->terms}.name LIKE ('%".$wpdb->escape( get_query_var('s') )."%')
) ";
}
return $where;
}
add_filter('posts_where', 'tax_search_where');
最后按帖子ID对结果进行分组,以避免因连接而导致重复结果
function tax_search_groupby( $groupby )
{
global $wpdb;
if( is_search() )
{
$groupby = "{$wpdb->posts}.ID";
}
return $groupby;
}
add_filter('posts_groupby', 'tax_search_groupby');
答案 1 :(得分:0)
这也可以通过将MySQL的 EXISTS 函数与子查询结合使用,该子查询将 term_relationships 与 terms 连接在一起。我创建了以下代码段并将其放入 functions.php :
// Search titles and tags
function and_extend_search( $search, &$wp_query ) {
global $wpdb;
if ( empty( $search ))
return $search;
$terms = $wp_query->query_vars[ 's' ];
$exploded = explode( ' ', $terms );
if( $exploded === FALSE || count( $exploded ) == 0 )
$exploded = array( 0 => $terms );
$search = '';
foreach( $exploded as $tag ) {
$search .= " AND (
($wpdb->posts.post_title LIKE '%$tag%')
OR EXISTS
(
SELECT
*
FROM
$wpdb->term_relationships
LEFT JOIN
$wpdb->terms
ON
$wpdb->term_relationships.term_taxonomy_id = $wpdb->terms.term_id
WHERE
$wpdb->terms.name LIKE '%$tag%'
AND
$wpdb->term_relationships.object_id = $wpdb->posts.ID
)
)";
}
return $search;
}
add_filter('posts_search', 'and_extend_search', 500, 2);