WordPress WP_Query search title only

I’m using WP_Query with “s” parameter, but it search all the fields in a post, and I only want to search the title in the post only. Not sure what is the proper way to do it?

$args = array(
    's' => $_POST['k'],
            'post_type' => 'my_post',
            "nopaging"=>true,
            'meta_query' => array(

            )
        );
$my_query = new WP_Query($args);

Related posts

Leave a Reply

2 comments

  1. We need to add filter to wordpress “posts_search”.

    Adding the following code to your active theme’s functions.php file will restrict WordPress search results to page and post titles only.

    //Limit Search to Post Titles Only

    function ni_search_by_title_only( $search, &$wp_query )
    {
    global $wpdb;
    if ( empty( $search ) )
        return $search; // skip processing - no search term in query
    $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->posts.post_title 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 );
    
  2. One interesting thing. If you want to work this on products you should use get_product_search_form hook.

    add_filter( 'get_product_search_form', 'ni_search_by_title_only', 500, 2 );
    

    In this way, the results should be given only from searching in Titles.