将WordPress搜索限制为单个ACF字段

时间:2019-06-14 作者:idleberg

我用过following filter 将ACF字段包括到我的搜索结果中。

add_filter( \'pre_get_posts\', \'so_9224493_adjust_search_query\');
function so_9224493_adjust_search_query( $query ) {
    if ( !is_admin() && $query->is_search ) { //the !is_admin() boolean ensures that this does not affect your dashboard
        $meta_query_arguments = array(
            array(
                \'key\' => \'item_number\', //this is where you would put your meta key
                \'value\' => $query->query_vars[\'s\'],
                \'compare\' => \'LIKE\',
            ),
        );
        $query->set(\'meta_query\', $meta_query_arguments);
    };
}
遗憾的是,它不起作用。然而,如果它确实有效,我想将搜索限制在该字段。我不想要帖子和页面的标题或内容等。

在这个过程中,我偶然发现a more promising filter, 所以我试着让它适应我的需要。

function ni_search_by_title_only( $search, &$wp_query ){
    global $wpdb;
    if ( empty( $search ) )
        return $search;
    $q = $wp_query->query_vars;
    $n = ! empty( $q[\'exact\'] ) ? \'\' : \'%\';
    $search =
    $searchand = \'\';
    foreach ( (array) $q[\'search_terms\'] as $term ) {
        $term = esc_sql( like_escape( $term ) );
        $search .= "{$searchand}($wpdb->postmeta.meta_value LIKE \'{$n}{$term}{$n}\')";
        $searchand = \' AND \';
    }
    if ( ! empty( $search ) ) {
        $search = " AND ({$search}) ";
        if ( ! is_user_logged_in() )
            $search .= " AND ($wpdb->posts.post_password = \'\') ";
    }
    return $search;
}
add_filter( \'posts_search\', \'ni_search_by_title_only\', 500, 2 );
这行不通。理想情况下,它不会搜索所有meta_value 字段,但仅指定meta_key.

附言:我对一个插件不感兴趣,因为它可以实现我想要的东西

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

最后我用了一个简单的meta_query:

$args = [
    \'post_status\'  => \'publish\',
    \'post_type\'    => $post_type,
    \'orderby\'      => \'title\',
    \'order\'        => \'ASC\',
    \'meta_query\' => array(
        \'relation\' => \'OR\',
        array(
            \'key\'           => \'my_acf_field\',
            \'value\'         => $search_term,
            \'compare\'       => \'LIKE\'
        ),
    )
];

$query = new WP_Query($args);