如何创建/修改 WP_Query 以在帖子标题或自定义字段中搜索?

ban*_*ing 2 wordpress title custom-fields

我需要修改或创建一个WP_Query将在帖子标题或自定义字段(称为“my_field”)中搜索搜索词的搜索项。

我已经阅读并尝试了几个小时,但我马上又回到了这段代码(如下),唉,它只在“my_field”中搜索,而没有考虑到这一点post_title

function my_pre_get_posts_2( $query ) {
 if ( is_admin() && $query->is_main_query() && $query->query['post_type'] === 'post' && isset($query->query['s']) ) {

    $search_word = $query->query['s'];

    $args = array(
        //'s' => $search_word, //If I include this line, the WP query seems to AND post_title and my_field. If I comment out this line, the WP query only searches in my_field. (I need WP to OR post_title and my_field.)
        'post_type' => 'post',
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key' => 'my_field',
                'value' => $search_word,
                'compare' => 'IN'
            ),
            array(
                'key' => 'post_title',
                'value' => $search_word,
                'compare' => 'IN',
            )
        )
    );

    //$query = new WP_Query( $args ); //Need to modify the existing WP_Query
    $query->init();
    $query->parse_query($args);
 }
}
add_action( 'pre_get_posts', 'my_pre_get_posts_2' );
Run Code Online (Sandbox Code Playgroud)

我需要这样做的原因是因为我需要修改“所有帖子”(管理)页面中“搜索帖子”按钮的行为,以便无论管理员用户搜索什么,它都会返回具有匹配帖子标题或 my_field 值。

ban*_*ing 5

为了进行 OR 搜索,我尝试合并两个单独的 WP_Query 结果,如下所示 - https://wordpress.stackexchange.com/questions/55519/can-i-merge-2-new-wp-queryvariable-s - 在 guidod 的答案中。但这并不是一个很好的解决方案,并且导致了不稳定的行为。

我发现的正确解决方案是使用 WP 自定义查询修改查询,如代码所示(需要一些修改) - http://codex.wordpress.org/Custom_Queries