TransWikia.com

How to exclude post body from WP search

WordPress Development Asked by nstampler on January 2, 2022

My WooCommerce site uses the default WP search. The one thing that I need to change is to exclude the post body from the search (in my case, the product description).

Right now, the search searches title, body, taxonomy terms. I want it to search only title and taxonomy terms.

To clarify, I don’t want to simply exclude the product description from displaying on the search resultspage. I want to stop the search engine from looking in the product description. ie: Search engine should only look for matches in the product name and taxonomy terms.

I searched high and low and can’t find info how to do this. Any suggestions?

Thanks!

One Answer

To remove elements from being searched, use the post_search filter to amend the SQL query for the search e.g. only pull in the title.

function ni_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', 'ni_search_by_title_only', 500, 2 );

Taken from https://nathaningram.com/restricting-wordpress-search-to-titles-only/

Personally I prefer a plugin for this as it gives me full control over every field I want in my search, the one I use is relevanssi. It should do what you want really easily.

Answered by Gareth Gillman on January 2, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP