I want to search according page and post title only. is it possible? my search code in header file is below
<form method="get" class="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="search" class="form-control" placeholder="<?php esc_attr_e( 'Search...', 'consulting' ); ?>" value="<?php echo esc_attr( get_search_query() ); ?>" name="s" /></div>
<button type="submit" style="height:7.5vh;"><i class="fa fa-search"></i></button>
</form>
You can search in post and page titles by adding below code to functions.php:
function __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 = ''; // this must be empty first
$searchand = '';
foreach ((array)$q['search_terms'] as $term) {
$term = esc_sql($wpdb->esc_like($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', '__search_by_title_only', 500, 2);
function __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($wpdb->esc_like($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', '__search_by_title_only', 500, 2);
Add this code in your theme functions.php file
in search.php use below query to override default search functionality or you can use custom template
$args = array(
'post_type' => 'post',
's' => $keyword,
'cat' => $catSearchID,
'tag' => $tag-slug,
'posts_per_page' => -1,
'location' => $post_location_search ,
);
$wp_query = new WP_Query($args);