将这些过滤器添加到functions.php
文件
/**
* Join posts and postmeta tables
*
* @link https://developer.wordpress.org/reference/hooks/posts_join/
*/
add_filter( \'posts_join\', function( string $sql, WP_Query $query ) {
global $wpdb;
if ( !is_admin() && $query->get( \'search_meta\' ) ) {
$sql .= \' LEFT JOIN \' . $wpdb->postmeta . \' ON \' . $wpdb->posts . \'.ID = \' . $wpdb->postmeta . \'.post_id \';
}
return $sql;
}, 10, 2 );
/**
* Modify the search query with posts_where
*
* @link https://developer.wordpress.org/reference/hooks/posts_where/
*/
add_filter( \'posts_where\', function( string $sql, WP_Query $query ) {
global $wpdb;
if ( !is_admin() && $query->get( \'search_meta\' ) ) {
$field_query = \'\';
if ( is_string( $query->get( \'search_meta\' ) ) ) {
$field_name = $query->get( \'search_meta\' );
$field_query = "AND {$wpdb->postmeta}.meta_key = \'{$field_name}\'";
}
$sql = preg_replace( \'/\\(\\s*\' . $wpdb->posts . \'.post_title\\s+LIKE\\s*(\\\'[^\\\']+\\\')\\s*\\)/\', \'(\' . $wpdb->posts . \'.post_title LIKE $1) OR (\' . $wpdb->postmeta . \'.meta_value LIKE $1\' . $field_query . \')\', $sql );
}
return $sql;
}, 10, 2 );
/**
* Prevent duplicates
*
* @link https://developer.wordpress.org/reference/hooks/posts_distinct/
*/
add_filter( \'posts_distinct\', function( string $sql, WP_Query $query ) {
if ( !is_admin() && $query->get( \'search_meta\' ) ) {
return \'DISTINCT\';
}
return $sql;
}, 10, 2 );
然后你只需要添加
search_meta
请求中的参数。要搜索所有元值,请使用
\'search_meta\' => true
...
add_action( \'wp_ajax_data_fetch\', \'data_fetch\' );
add_action( \'wp_ajax_nopriv_data_fetch\', \'data_fetch\' );
function data_fetch() {
$recipes = new WP_Query( [
\'post_type\' => \'project5\',
\'orderby\' => \'rand\',
\'post_status\' => \'publish\',
\'s\' => esc_attr( $_POST[\'keyword\'] ),
\'search_meta\' => true
] );
}
或搜索特定字段值使用
\'search_meta\' => \'MY_FIELD_NAME\'
...
add_action( \'wp_ajax_data_fetch\', \'data_fetch\' );
add_action( \'wp_ajax_nopriv_data_fetch\', \'data_fetch\' );
function data_fetch() {
$recipes = new WP_Query( [
\'post_type\' => \'project5\',
\'orderby\' => \'rand\',
\'post_status\' => \'publish\',
\'s\' => esc_attr( $_POST[\'keyword\'] ),
\'search_meta\' => \'keyword\' // Name of custom meta_key
] );
}
这还没有完全测试过,所以请记住这一点。
<小时>
EDIT
一种“不太过分”的方法是在WP\\u查询中使用元参数(
docs here). 例如
add_action( \'wp_ajax_data_fetch\', \'data_fetch\' );
add_action( \'wp_ajax_nopriv_data_fetch\', \'data_fetch\' );
function data_fetch() {
$input = esc_attr( $_POST[ \'keyword\' ] );
$recipes = new WP_Query( [
\'post_type\' => \'project5\',
\'orderby\' => \'rand\',
\'post_status\' => \'publish\',
\'s\' => $input,
\'meta_key\' => \'MY_CUSTOM_FIELD_DATABSE_KEY\',
\'meta_value\' => $input,
\'meta_compare\' => \'LIKE\'
] );
}