如何在钩子PRE_GET_POST中的WP_QUERY中执行多个搜索(使用逻辑或)?

时间:2021-07-21 作者:Мегакот

示例:

$query->set(\'s\', \'foo bar\'); - 搜索foo bar

我想将搜索设置为foo barlorem ipsum dolorping pong

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

你可以这样做

add_action(\'pre_get_posts\', \'bt_search_posts\');

function bt_search_posts ($query) {
    // the posts ids that contain foo bar OR lorem ipsum dolor OR ping pong
    $posts_ids = [];

    // get the current query vars
    $query_vars = $query->query_vars;

    // loop each term we want to search and if found, add the post id into the array
    foreach ([\'foo bar\', \'lorem ipsum dolor\', \'ping pong\'] as $search_term) {
        // add the search term to the query vars
        $query_vars[\'s\']      = $search_term;

        // we only need posts ids so we set that
        $query_vars[\'fields\'] = \'ids\';

        // loop through found posts, if not found we will have a empty array so no problem
        foreach (get_posts($query_vars) as $post_id) {
            $posts_ids[] = $post_id;
        }
    }

    // set post__in to the posts ids that we found that matched the search terms we provided
    if (!empty($posts_ids)) $query->set(\'post__in\', $posts_ids);
}
我不知道您要在何处运行此查询,因此您需要添加适当的检查,以免干扰其他WP_Query, 像主要的WordPress查询之类的。

一个好的开始检查应该是

if (!is_admin() && $query->is_main_query()) {
    // code here
}
但如果您已经有了一个最适合您的,请使用它=]

相关推荐

如何在unction.php中更改图片url?

例如,我的图像url是https://aa.com/wp-content/uploads/2021/07/x-600x600.jpg我想把它改成https://images.s3.us-east-2.amazonaws.com/aa.com/wp-content/uploads/2021/07/x-600x600.jpg或https://images.s3.us-east-2.amazonaws.com/aa.com/wp-content/uploads/2021/07/x-600x600.jpg.web