我需要在wordpress搜索结果中添加自定义字段。
我尝试使用pre\\u get\\u posts过滤器,如下所示:
function search_filter( $query ) {
$key_fields = array ( \'buty\' );
$value_field = $query->query_vars[\'s\'];
$query->query_vars[\'s\'] = \'\';
if ( $value_field != \'\' ) {
$filter_query = array( \'relation\' => \'OR\' );
foreach ( $key_fields as $one_field ) {
array_push ( $filter_query , array (
\'key\' => $one_field,
\'value\' => $value_field,
\'compare\' => \'LIKE\'
) );
}
$query->set( \'meta_query\' , $filter_query );
}
}
add_filter( \'pre_get_posts\' , \'search_filter\');
它可以工作,但现在搜索不适用于帖子标题和帖子内容
所以问题是:如何在不丢失标准功能的情况下,正确地将自定义字段添加到Wordpress搜索结果中?
最合适的回答,由SO网友:nmr 整理而成
Wordpress搜索posts
桌子您必须通过添加postmeta
表(使用左连接),然后将您自己的条件添加到WHERE子句。
<?php
/**
* Extend WordPress search to include custom fields
*
* https://adambalee.com
*/
/**
* Join posts and postmeta tables
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join
*/
function cf_search_join( $join ) {
global $wpdb;
if ( is_search() ) {
$join .=\' LEFT JOIN \'.$wpdb->postmeta. \' ON \'. $wpdb->posts . \'.ID = \' . $wpdb->postmeta . \'.post_id \';
}
return $join;
}
add_filter(\'posts_join\', \'cf_search_join\' );
/**
* Modify the search query with posts_where
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where
*/
function cf_search_where( $where ) {
global $pagenow, $wpdb;
$key_fields = array ( \'buty\' );
if ( is_search() )
$where = preg_replace(
"/\\(\\s*".$wpdb->posts.".post_title\\s+LIKE\\s*(\\\'[^\\\']+\\\')\\s*\\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR ("
.$wpdb->postmeta. ".meta_value LIKE $1 AND "
.$wpdb->postmeta. ".meta_key IN (\'" .implode("\',\'", $key_fields). "\') )", $where );
}
return $where;
}
add_filter( \'posts_where\', \'cf_search_where\' );
/**
* Prevent duplicates
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct
*/
function cf_search_distinct( $where ) {
global $wpdb;
if ( is_search() ) {
return "DISTINCT";
}
return $where;
}
add_filter( \'posts_distinct\', \'cf_search_distinct\' );
详情可在此处找到
"Search WordPress by Custom Fields without a Plugin"