最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Altering search results to handle a post meta field not working in current WordPress

programmeradmin4浏览0评论

I have the following code (based on examples from various other places on the web) It's definitely updating the query but it just doesn't return any results.

Am I using the wrong hook ?

function custom_search_query( $q ) {
    if ( $q->is_search ) {
        $meta_query = $q->get( 'meta_query' );
        $meta_query[] = array(
            'key' => 'custom_meta_key_name_here',
            'value' => $q->query_vars['s'],
            'compare' => 'LIKE',
            'type'      => 'TEXT',
        );
        $q->set( 'meta_query', $meta_query );
    };
}
add_action( 'pre_get_posts', 'custom_search_query');

I have the following code (based on examples from various other places on the web) It's definitely updating the query but it just doesn't return any results.

Am I using the wrong hook ?

function custom_search_query( $q ) {
    if ( $q->is_search ) {
        $meta_query = $q->get( 'meta_query' );
        $meta_query[] = array(
            'key' => 'custom_meta_key_name_here',
            'value' => $q->query_vars['s'],
            'compare' => 'LIKE',
            'type'      => 'TEXT',
        );
        $q->set( 'meta_query', $meta_query );
    };
}
add_action( 'pre_get_posts', 'custom_search_query');
Share Improve this question asked Dec 13, 2019 at 17:41 AdamJonesAdamJones 3282 gold badges7 silver badges26 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

I got this working through the following combination of functions (credit to this post):

function search_join_custom( $join ) {
    global $wpdb;
    if ( is_search() ) {
        $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
    }
    return $join;
}
add_filter('posts_join', 'search_join_custom' );
function search_where_custom( $where ) {
    global $pagenow, $wpdb;
    if ( is_search() ) {
        $where = preg_replace(
            "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
            "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_key='YOUR_KEY_NAME' AND ".$wpdb->postmeta.".meta_value LIKE $1)", $where );
    }
    return $where;
}
add_filter( 'posts_where', 'search_where_custom' );
function search_distinct_custom( $where ) {
    global $wpdb;
    if ( is_search() ) {
        return "DISTINCT";
    }
    return $where;
}
add_filter( 'posts_distinct', 'search_distinct_custom' );
发布评论

评论列表(0)

  1. 暂无评论