我试图找出如何在自定义搜索中放宽与字符串搜索匹配的自定义元字段。
基本上,如果自定义帖子的元字段有“Whistler Bike Park,Canada”,并且我输入了它,我将在搜索中返回帖子。但如果我只输入“Whistler”,那么我什么也得不到。
我认为需要编辑的关键行如下:
$where .= " OR (( $wpdb->postmeta.meta_key = \'$meta_key\' AND $wpdb->postmeta.meta_value = \'$meta_value\' ))";
这是完整的pre\\u get\\u post()挂钩。
add_action(\'pre_get_posts\', \'site_search_query\');
function site_search_query( $query )
{
if (!is_admin() && $query->is_main_query() ) :
if ( $query->is_search ) :
// if just a normal search and no in spanish - return
// we need to make exception for normal search and is spanish for spanish titles
// since those are meta values
if( ( count($_GET) == 1 ) && ( ICL_LANGUAGE_CODE != "es" ) )
return;
$s = preg_replace( "/[^a-zA-Z0-9\\s]/", "", $_GET[\'s\'] ); // sanitize and get search string;
unset( $_GET[\'s\'] );
$params = array();
foreach( $_GET as $key => $param ) :
$params[$key] = preg_replace( "/[^a-z0-9.]+/i", "", $param );
endforeach;
$meta_queries = array();
foreach( $params as $param ) :
switch( $param ) :
case \'org\':
$param = \'organization\';
break;
case \'desc\':
$param = \'basic_info_long_description_in_english\';
break;
endswitch;
$args = array(
\'key\' => $param,
\'value\' => $s,
\'compare\' => \'LIKE\'
);
array_push( $meta_queries, $args );
endforeach;
$query->set( \'post_type\', \'project\' );
$query->set( \'meta_query\', array( $args ) );
/**
* Apparently this is a hack to allow for search by post meta in meta_query for pre_get_post $query->set()
* See: http://wpthemetutorial.com/2014/07/17/using-pre_get_posts-meta_query/
* this is done as an anonymous function so we can pass it local vars
* @param string
* @param complex array
* @param function
* @return string
*/
$custom_filter = function( $where = \'\' ) use( $meta_queries, $custom_filter )
{
global $wpdb;
foreach( $meta_queries as $meta_query ) :
$meta_key = $meta_query[\'key\'];
$meta_value = $meta_query[\'value\'];
// too restrictive
$where .= " OR (( $wpdb->postmeta.meta_key = \'$meta_key\' AND $wpdb->postmeta.meta_value = \'$meta_value\' ))";
// too loose
//$where .= " OR (( $wpdb->postmeta.meta_key = \'$meta_key\' ))";
endforeach;
remove_filter( \'posts_where\', $custom_filter );
return $where;
};
add_filter( \'posts_where\', $custom_filter );
endif; // is_search
endif; // is not admin && is main query
} // site_search_query
欢迎提出任何建议。