user1187968
user1187968

Reputation: 8026

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);

Upvotes: 4

Views: 5909

Answers (3)

Jan_Lukas
Jan_Lukas

Reputation: 38

I have found this comment on the WP_Query documentation page. You can now use the currently undocumented search_columns parameter (introduced in 6.2.0), to restrict your search to specific parts of the post.

$args = array(
   's' => 'your search term',
   'search_columns' => array('post_title') // You can add 'post_name' or 'post_content' to include slugs or content
);
$my_query = new WP_Query($args);

Upvotes: 0

beamkiller
beamkiller

Reputation: 188

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.

Upvotes: 0

Suyash Jain
Suyash Jain

Reputation: 571

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 );

Upvotes: 2

Related Questions