这是目前最简单、最有效的解决方案。以上这些都不适合我。是的tested and working with Wordpress 5.3.1 .
在函数中放置以下代码。要挂接到的php文件posts_clauses
滤器
/**
* Include meta fields in search
*
* @author Mindaugas // meevly.com
* @link https://meevly.com/services/custom-wordpress-themes-and-plugins/
*
* @param array $pieces query pieces.
* @param WP_Query $args query object.
* @return array
*/
function mv_meta_in_search_query( $pieces, $args ) {
global $wpdb;
if ( ! empty( $args->query[\'s\'] ) ) { // only run on search query.
$keywords = explode(\' \', get_query_var(\'s\'));
$escaped_percent = $wpdb->placeholder_escape(); // WordPress escapes "%" since 4.8.3 so we can\'t use percent character directly.
$query = "";
foreach ($keywords as $word) {
$query .= " (unique_postmeta_selector.meta_value LIKE \'{$escaped_percent}{$word}{$escaped_percent}\') OR ";
}
if ( ! empty( $query ) ) { // append necessary WHERE and JOIN options.
$pieces[\'where\'] = str_replace( "((({$wpdb->posts}.post_title LIKE \'{$escaped_percent}", "( {$query} (({$wpdb->posts}.post_title LIKE \'{$escaped_percent}", $pieces[\'where\'] );
$pieces[\'join\'] = $pieces[\'join\'] . " INNER JOIN {$wpdb->postmeta} AS unique_postmeta_selector ON ({$wpdb->posts}.ID = unique_postmeta_selector.post_id) ";
}
}
return $pieces;
}
add_filter( \'posts_clauses\', \'mv_meta_in_search_query\', 20, 2 );
您的查询应该如下所示。
Please note that suppress_filters => false
is mandatory! 没有它,它就无法工作。
$search_posts_array = array(
\'suppress_filters\' => false,
\'s\' => $keyword,
);
$search_results = get_posts( $search_posts_array );