无插件实现wordpress搜索自定义字段

前段时间有个客户反映,网站搜索搜产品标题能搜出结果,但是如果搜索产品编号(备注:产品编号用自定义字段实现)是搜不出结果的,对于用户的体验不是很好。

确实,文章自定义字段保存在postmeta表中,而wordpress搜索仅会搜索文章表即posts表。

于是google了一下,有现成的解决代码,我就又当一回搬运工。

Search WordPress by Custom Fields without a Plugin

第一步:链接查询

也就是修改搜索查询的sql代码,将postmeta表左链接进去。

  1. /**
  2.  * Join posts and postmeta tables
  3.  *
  4.  * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join
  5.  */
  6. function cf_search_join( $join ) {
  7.   global $wpdb;
  8.   if ( is_search() ) {
  9.     $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
  10.   }
  11.   return $join;
  12. }
  13. add_filter('posts_join', 'cf_search_join' );

第二步:查询代码

 在wordpress查询代码中加入自定义字段值的查询。
  1. /**
  2.  * Modify the search query with posts_where
  3.  *
  4.  * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where
  5.  */
  6. function cf_search_where( $where ) {
  7.   global $pagenow$wpdb;
  8.   if ( is_search() ) {
  9.     $where = preg_replace(
  10.       "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
  11.       "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)"$where );
  12.   }
  13.   return $where;
  14. }
  15. add_filter( 'posts_where', 'cf_search_where' );

第三步:去重

搜索结果很有可能有重复的,所以需要去重,很简单,在sql语句中加入DISTINCT关键字。

  1. /**
  2.  * Prevent duplicates
  3.  *
  4.  * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct
  5.  */
  6. function cf_search_distinct( $where ) {
  7.   global $wpdb;
  8.   if ( is_search() ) {
  9.     return "DISTINCT";
  10.   }
  11.   return $where;
  12. }
  13. add_filter( 'posts_distinct', 'cf_search_distinct' );

总结:

依次将上面三步骤中的代码加入到主题的functions.php文件中即可。

END

已有2条评论

发表评论