0

I'm trying to extend the wordpress search to include a custom cpt through the meta value associated using an ACF. All seems to works great, but the main problem's that I have to add this code to make the function working:

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

seems that for some reason is not possible search also for title and the post content, but I need to return the post that match as condition the post within a certain id and a certain title or post content.

This is the code:

function search_custom_cpt( $search_term ) {
    global $wpdb;
    $post_type = 'doctor';
    $search_term = '%' . $wpdb->esc_like( $search_term ) . '%';
    $post_ids = $wpdb->get_col( $wpdb->prepare( "
        SELECT ID
        FROM $wpdb->posts
        WHERE post_type = %s
        AND post_status = 'publish'
        AND post_title LIKE %s
    ", $post_type, $search_term ) );
    return $post_ids;
}

function add_related_posts_to_search( $query ) {
    if(!is_admin() && $query->is_search && $query->is_main_query()) { 
        $search_term = $query->query_vars['s'];
        $query->query_vars['s'] = '';
        $post_ids = search_custom_cpt( $search_term );

        if( ! empty( $post_ids ) ) {
            $meta_query = array(
                'relation' => 'OR'
            );

            foreach($post_ids as $pi) {
                $meta_query[] = array(
                    'key' => 'medici',
                    'value' => sprintf('%s', $pi),
                    'compare' => 'LIKE',
                );
            }

            $query->set('meta_query', $meta_query);
        }
    }
}
add_action( 'pre_get_posts', 'add_related_posts_to_search' );

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.