AnswerBun.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!

Related Questions

How to make repeated component/block in Gutenberg

1  Asked on January 1, 2021 by paranoid-android

   

How do I get the category URL from get_the_category?

2  Asked on December 28, 2020 by egr103

       

$wpdb -> Batch insert from XML File?

3  Asked on December 27, 2020 by click-here

         

lazy load comments wordpress on click

1  Asked on December 27, 2020 by sa-eu

   

Hook to use when customer placing order

1  Asked on December 26, 2020 by kevsterino

 

WordPress Ajax Custom Query – High CPU LOAD

0  Asked on December 22, 2020 by techn9ne

     

Update to older wordpress version from admin?

4  Asked on December 20, 2020 by hakre

   

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir