Including Custom Post Types in Search Results

Couple of days back, in one of my post, I have shown how to include Custom Post Type (CPT) to default RSS feed. Today, I will show how to add CPT to default search results.

The following snippet code will add your CPT to your blog’s search results. All you need to do is, copy and paste the following snippet on your theme’s functions.php file and update it.

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

However, do not forget the change the CPT with your custom post type slug from the post_type array. If you have multiple CPT registered on your site, you can also add them as well.

Once you are done, you can check the search results with one of your custom post title. Hope this snippet helps.

Source: WordPress Codex.

Today In History



Leave a Reply

Note: Convet HTML, PHP, JavaScripts from HTMLify, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.