0

So I have this from Query Monitor:

AND (((zp_posts.post_title LIKE '%mercedes%')
OR (zp_posts.post_excerpt LIKE '%mercedes%')
OR (zp_posts.post_content LIKE '%mercedes%'))) 
AND zp_posts.post_type IN ('post', 'page', 'attachment')
AND (zp_posts.post_status = 'publish'
OR zp_posts.post_author = 1
AND zp_posts.post_status = 'private') 
ORDER BY zp_posts.post_title LIKE '%mercedes%' DESC, zp_posts.post_date DESC

I would like the searches queries to target only post_title and post_content, exclude all others parts. Any idea in achieving that?

  • what is that? there is no wordpress core API that will generate such a query. – Mark Kaplun Sep 24 '17 at 13:24
  • what is what? I was asking how to exclude everything else, except posts, from search results. – Ciprian Sep 24 '17 at 23:21
  • your query can not be fast. if this is a query you written on your own, whatever you are trying to do is wrong. If this is a plugin you use... well without the actual code it will be impossible to help you change it – Mark Kaplun Sep 25 '17 at 1:46
  • Query Monitor gives me a very similar query on a search page /?s. I don't have any plugins or custom functions that would affect search. The caller is WP_Query->get_posts – Slam Feb 13 '18 at 21:55
1

You should be able to use pre_get_posts to change the query. I'd suggest creating a custom plugin, so that if you ever change your theme your modifications will still apply.

To get you started, here's how you can set the post types being searched:

function search_filter($query) {
  if ( !is_admin() && $query->is_main_query() ) {
    if ($query->is_search) {
      $query->set('post_type', array( 'post' ) );
    }
  }
}

add_action('pre_get_posts','search_filter');

You would continue to add $query->set statements inside the conditionals to further customize what fields to search.

One other option would be to write a completely custom query and call that from your search rather than using WP's built-in query. You might want to benchmark that solution to see whether it is any faster than the pre_get_posts way.

  • if ( !is_admin() ? – Ciprian Sep 25 '17 at 14:11
  • Queries run in wp-admin too. This prevents it from causing issues in admin, restricting it to the main query only on the front end. – WebElaine Sep 25 '17 at 15:05
  • @WebElaine or @Ciprian, can you post the code that limits the search to only specified fields like post_content? Thanks! – Slam Feb 13 '18 at 22:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.