Search code examples
phpwordpresscustom-post-type

WordPress exact search query


I need to search for the exact title. but my code sometime fetch similar title which is like

I love him, I love, I love my country,

I need only search the second title "I love". How can I achieve this?

 $title= "I love";
    global $post;
    $args = array(
        'post_type' => 'course',
        "s" => $title,
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'meta_key' => 'vibe_product',
        'meta_value' => ' ',
        'meta_compare' => '!=',
    );

Solution

  • You can pass the code below in your functions.php

    add_filter( 'posts_where', 'custom_posts_where', 10, 2 );
    function custom_posts_where( $where, &$wp_query )
    {
        global $wpdb;
        if ( $specific_title = $wp_query->get( 'specific_title' ) ) {
            $where .= ' AND ' . $wpdb->posts . '.post_title = \'' . esc_sql( $wpdb->esc_like( $specific_title ) ) . '\'';
        }
        return $where;
    }
    

    and then use the get_posts or wp query function like this:

    $title= "I love";
    global $post;
    $args = array(
        'post_type' => 'course',
        "specific_title" => $title,
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'meta_key' => 'vibe_product',
        'meta_value' => ' ',
        'meta_compare' => '!=',
    );