limit wordpress search to title

Solutions on MaxInterview for limit wordpress search to title by the best coders in the world

showing results for - "limit wordpress search to title"
Devon
08 May 2019
1// Place this in function.php
2function search_by_title( $search, $wp_query ) {
3    if ( ! empty( $search ) && ! empty( $wp_query->query_vars['search_terms'] ) ) {
4        global $wpdb;
5
6        $q = $wp_query->query_vars;
7        $n = ! empty( $q['exact'] ) ? '' : '%';
8
9        $search = array();
10
11        foreach ( ( array ) $q['search_terms'] as $term )
12            $search[] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $n . $wpdb->esc_like( $term ) . $n );
13
14        if ( ! is_user_logged_in() )
15            $search[] = "$wpdb->posts.post_password = ''";
16
17        $search = ' AND ' . implode( ' AND ', $search );
18    }
19
20    return $search;
21}
22
23
24$args = array(
25    's' => 'search string',
26    'numberposts' => 5,
27    'offset' => 0,
28    'category' => 0,
29    'orderby' => 'post_date',
30    'order' => 'DESC',
31    'post_type' => 'post',
32    'post_status' => 'publish',
33    'suppress_filters' => true);
34
35add_filter( 'posts_search', 'search_by_title', 10, 2 );
36$recent_posts = wp_get_recent_posts($args, ARRAY_A);
37remove_filter( 'posts_search', 'search_by_title', 500 );