我想添加一个自定义字段(“introduction”和“ensavoirplus”)来搜索Wordpress,但SQL代码并不精确。我不明白我是否犯了错误,或者WP不能做到这一点。但我的尝试失败了。。。我不知道为什么,因为我完全按照抄本上说的去做。
这是我的代码:
function recherche_avancee( $query ) {
if ( !is_admin() && $query->is_search ) {
$custom_fields = array(
"introduction",
"en_savoir_plus_page"
);
$meta_query = array(\'relation\' => \'OR\');
foreach($custom_fields as $cf) {
array_push($meta_query, array(
\'key\' => $cf,
\'value\' => $_GET[\'s\'],
\'compare\' => \'LIKE\'
));
}
$query->set("meta_query", $meta_query);
}
}
add_action( \'pre_get_posts\', \'recherche_avancee\');
这是SQL代码:
1. SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
2. FROM wp_posts
3. INNER JOIN wp_postmeta
4. ON ( wp_posts.ID = wp_postmeta.post_id )
5. WHERE 1=1
6. AND (((wp_posts.post_title LIKE \'%environnement%\')
7. OR (wp_posts.post_content LIKE \'%environnement%\')))
8. AND wp_posts.post_type IN (\'post\', \'page\', \'attachment\')
9. AND (wp_posts.post_status = \'publish\'
10. OR wp_posts.post_status = \'miseenavant\'
11. OR wp_posts.post_author = 3
12. AND wp_posts.post_status = \'private\')
13. AND ( ( wp_postmeta.meta_key = \'introduction\'
14. AND CAST(wp_postmeta.meta_value AS CHAR) LIKE \'%environnement%\' )
15. OR ( wp_postmeta.meta_key = \'en_savoir_plus_page\'
16. AND CAST(wp_postmeta.meta_value AS CHAR) LIKE \'%environnement%\' ) )
17. GROUP BY wp_posts.ID
18. ORDER BY wp_posts.menu_order ASC
19. LIMIT 0, 10
错误在第13行,因为我不想要
AND 但是
OR 第13、14、15、16行应该紧跟在第7行之后,一切正常。
有人已经犯了同样的错误,如果是,那是从哪里来的?
谢谢
SO网友:ArnaudBan
借助WordPress 4.1,您可以更好地进行meta\\u查询:https://make.wordpress.org/core/2014/10/20/update-on-query-improvements-in-4-1/
function recherche_avancee($query) {
if (!is_admin() && $query->is_search) {
$meta_query = array(
\'relation\' => \'OR\',
array(
\'relation\' => \'OR\',
array(
\'key\' => \'introduction\',
\'value\' => get_search_query(),
\'compare\' => \'LIKE\',
),
array(
\'key\' => \'en_savoir_plus_page\',
\'value\' => get_search_query(),
\'compare\' => \'LIKE\',
),
),
);
$query->set(\'meta_query\', $meta_query);
}
}
add_action(\'pre_get_posts\', \'recherche_avancee\');
没有测试,但你明白了。。。