我在用功能搜索我的post_meta
我会将其存储在每个帖子中,但问题是当我搜索时title
, tags
, 内容,然后搜索不起作用。我想我的新function
只需覆盖wordpress的默认搜索。这是我的密码
function custom_search_query( $query ) {
$custom_fields = array(
// put all the meta fields you want to search for here
"post_state",
"post_region",
"post_country"
);
$searchterm = $query->query_vars[\'s\'];
// we have to remove the "s" parameter from the query, because it will prevent the posts from being found
$query->query_vars[\'s\'] = "";
if ($searchterm != "") {
$meta_query = array(\'relation\' => \'OR\');
foreach($custom_fields as $cf) {
array_push($meta_query, array(
\'key\' => $cf,
\'value\' => $searchterm,
\'compare\' => \'LIKE\'
));
}
$query->set("meta_query", $meta_query);
}
}
add_filter( "pre_get_posts", "custom_search_query");
那么我错在哪里呢。你知道我怎样才能搜索到所有的东西吗。我的自定义
post_meta
,
title
,
tags
,
categories
,
content
.
最合适的回答,由SO网友:Sumit 整理而成
最好修改Wordpress search SQL查询,而不是添加额外的元查询
试试这个:
function search_distinct($distinct) {
$distinct = \'DISTINCT\';
return $distinct;
}
function join_table($join){
global $wpdb;
$join .= "LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) ";
return $join;
}
function search_into_post_meta( $search, $wp_query )
{
if ( is_search() ) {
global $wpdb;
if ( empty( $search ) )
return $search;
$q = $wp_query->query_vars;
$n = ! empty( $q[\'exact\'] ) ? \'\' : \'%\';
$search =
$searchand = \'\';
foreach ( (array) $q[\'search_terms\'] as $term ) {
$term = esc_sql( like_escape( $term ) );
$search .= "{$searchand} ( ($wpdb->posts.post_title LIKE \'{$n}{$term}{$n}\') OR ($wpdb->posts.post_content LIKE \'{$n}{$term}{$n}\') OR ($wpdb->postmeta.meta_key = \'post_state\' AND $wpdb->postmeta.meta_value LIKE \'{$n}{$term}{$n}\') OR ($wpdb->postmeta.meta_key = \'post_region\' AND $wpdb->postmeta.meta_value LIKE \'{$n}{$term}{$n}\') OR ($wpdb->postmeta.meta_key = \'post_country\' AND $wpdb->postmeta.meta_value LIKE \'{$n}{$term}{$n}\'))";
$searchand = \' AND \';
}
if ( ! empty( $search ) ) {
$search = " AND ({$search}) ";
if ( ! is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password = \'\') ";
}
add_filter(\'posts_distinct_request\', \'search_distinct\');
add_filter(\'posts_join_request\',\'join_table\');
return $search;
}
return $search;
}
add_filter( \'posts_search\', \'search_into_post_meta\', 500, 2 );