如何修改wordpress搜索以查询分类术语和类别术语? [英] How to amend wordpress search so it queries taxonomy terms and category terms?

查看:31
本文介绍了如何修改wordpress搜索以查询分类术语和类别术语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修改搜索,所以如果说我有一个名为作者"的分类法并在帖子中添加了Ian Rankin"的术语,如果我搜索Ian Rankin",我希望该帖子出现.我想目前它只搜索标题和内容.我怎样才能让它成为搜索词?

I want to amend the search so if say I have taxonomy called "author" and add a term of "Ian Rankin" to a post, if I search for "Ian Rankin", I want that post to come up. I guess at the moment it only searches titles and content. How can I make it search terms too?

推荐答案

您可以使用过滤器挂钩更改搜索查询以加入分类表.

You can alter the search query using filter hooks to join the taxonomy tables.

例如还可以搜索作者"分类法

e.g. to also search on the 'author' taxonomy

首先加入分类表

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');

然后在分类法作者"中找到搜索词

then find the search term in the taxonomy 'author'

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');

最后按post id对结果进行分组,避免因join导致重复结果

and finally group the results by post id to avoid duplicate results because of the join

function tax_search_groupby( $groupby )
{
  global $wpdb;
  if( is_search() )
  {
    $groupby = "{$wpdb->posts}.ID";
  }
  return $groupby;
}
add_filter('posts_groupby', 'tax_search_groupby');

这篇关于如何修改wordpress搜索以查询分类术语和类别术语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆