How to search only in post title - wp_query

Viewed 13653

I added a text field to the posts filter form and I use s= parameter to make the search work. But how to search only in the title of the post (not in the content)?

HTML:

<input type="text" name="search" placeholder="Search..." value="">
<button>Filter</button>

PHP:

    $args = array(
        'post_type' => $_POST['posttype'], 
        'orderby' => $_POST['orderby'], 
        'order' => $_POST['order'],
        's' => $_POST['search']
    );
1 Answers

Locate the file you need the search function implemented on and add the code below to your file.

$args = array(
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'orderby' => $_POST['orderby'], 
    'order' => $_POST['order'],
    'search_prod_title' => $_POST['search'],
);
add_filter( 'posts_where', 'title_filter', 10, 2 );
$query = new WP_Query($args);
remove_filter( 'posts_where', 'title_filter', 10, 2 );

To search title in your WordPress query, you need to add a function to your WordPress theme’s functions.php file.

function title_filter( $where, &$wp_query ){
    global $wpdb;
    if ( $search_term = $wp_query->get( 'search_prod_title' ) ) {
        $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $search_term ) ) . '%\'';
    }
    return $where;
}
Related