Manipulating a query

时间:2013-10-08 作者:revo

我正在尝试使用自己的搜索表单,而不是默认的单字段表单。因此,我创建了字段,并使用pre_get_posts

一切都很好。因为搜索了多个custom fields 我正在使用meta_query 具有relation => \'OR\' 以及在其中使用多个键/值数组。

但有一个问题我已经并将要解释。这是单击“提交”按钮时将运行的查询:

SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID FROM wp_posts  INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id)
INNER JOIN wp_postmeta AS mt2 ON (wp_posts.ID = mt2.post_id)
INNER JOIN wp_postmeta AS mt3 ON (wp_posts.ID = mt3.post_id)
INNER JOIN wp_postmeta AS mt4 ON (wp_posts.ID = mt4.post_id)
INNER JOIN wp_postmeta AS mt5 ON (wp_posts.ID = mt5.post_id)
INNER JOIN wp_postmeta AS mt6 ON (wp_posts.ID = mt6.post_id) WHERE 1=1  AND (((wp_posts.post_title LIKE \'%test%\') OR (wp_posts.post_content LIKE \'%test%\')))  AND wp_posts.post_type IN (\'post\', \'page\', \'attachment\') AND (wp_posts.post_status = \'publish\' OR wp_posts.post_author = 1 AND wp_posts.post_status = \'private\') AND ( (wp_postmeta.meta_key = \'jz_ftype\' AND CAST(wp_postmeta.meta_value AS CHAR) = \'pamphlet\')
OR  (mt1.meta_key = \'jz_year\' AND CAST(mt1.meta_value AS CHAR) = \'\')
OR  (mt2.meta_key = \'jz_has-answer\' AND CAST(mt2.meta_value AS CHAR) = \'yes\')
OR  (mt3.meta_key = \'jz_atc-author\' AND CAST(mt3.meta_value AS CHAR) LIKE \'%%\')
OR  (mt4.meta_key = \'jz_ebook-author\' AND CAST(mt4.meta_value AS CHAR) LIKE \'%%\')
OR  (mt5.meta_key = \'jz_pro-author\' AND CAST(mt5.meta_value AS CHAR) LIKE \'%%\')
OR  (mt6.meta_key = \'jz_level\' AND CAST(mt6.meta_value AS CHAR) = \'basic\') ) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10
如您所见(在第7行末尾),我通过使用$query->set() 方法正在AND:

AND ( (wp_postmeta.meta_key = \'jz_ftype\' AND CAST(wp_postmeta.meta_value AS CHAR) = \'pamphlet\')
但我必须做到OR:

OR ( (wp_postmeta.meta_key = \'jz_ftype\' AND CAST(wp_postmeta.meta_value AS CHAR) = \'pamphlet\')
那么我如何才能做到这一点呢?

1 个回复
最合适的回答,由SO网友:birgire 整理而成

您可以尝试添加posts_where 在您的pre_get_posts 挂钩:

function my_pre_get_posts( $q ){
    if( $q->is_main_query() )
        add_filter( \'posts_where\', \'my_posts_where\' );

    return $q;
}
! is_admin() && add_action( \'pre_get_posts\', \'my_pre_get_posts\' );
在哪里

function my_posts_where( $where ){

    // your custom replacements on the $where string
    // ...

    // remove the filter           
    remove_filter( current_filter() , __FUNCTION__ );

    return $where;
}

结束

相关推荐

Get_Search_link()重定向到404模板页面

我构建了一个自定义主题,其中有一个404。php页面和搜索。php页面。在模板的其他地方,我想直接链接到搜索页面。因此,我使用get\\u search\\u template()函数来获取搜索页面链接,其结果如下:http://example.org/search当我单击链接时,我会被发送到404页面模板。为什么会转到404页面模板而不是搜索页面模板?