Search Post Title Using wp_query
Performing search operations is important for users to get the most optimized results so they perform fewer actions and reach the desired results. One of the ways to provide this optimized search on Wordpress is to do searching only based on the post titles using wp_query search titles. This is because most of the time, the user search keyword is related to the post titles, in turn, giving out the most desired results.
To perform only the post title search we need to create or modify the theme’s functions.php I,e using wp_query search titles with the following code.
function wcs_search_by_title_only( $search, &$wp_query ) { global $wpdb; if ( empty( $search ) ) return $search; $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', 'wcs_search_by_title_only', 500, 2 );
Adding this code snippet (wp_query search titles) in your functions.php will first check if the search is returning a result or not. If it is returning any result then, it will perform an SQL query which will try matching the user keywords with the post title and return the matched results.
Though there are many ways to search using the titles, an easier way to do this is by using WP fastest site search plugin by Expertrec
- Install WP fastest site search plugin from WordPress plugin store.
- Go to https://cse.expertrec.com/newuser?platform=wordpress.
- Enter your WordPress website URL and click on next->
- The crawl will start in the background.
- Login to your WordPress admin panel.
- In your left panel you must be able to see expertrec’s WordPress plugin, click on that.
- Get your site ID (or) API key from your expertrec control panel ( here ).
- Copy-paste your site id in your WordPress control panel and click on save changes.
- Make sure you have upgraded to a paid plan before 15 days of free trial. (Price begins at 9 USD per month)
- That’s it! Your brand new WordPress search is up and running.
Add great search to your wordpress site at 9 USD per month
Watch this video to learn more about having all posts on one page