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.
<?php
function add_cpt_search($query) {
if (!is_admin() && $query->is_main_query()) {
if ($query->is_search) {
$query->set('post_type', array('post','cpt')); } } }
add_action('pre_get_posts','add_cpt_search');
?>
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.
Comment
Leave a Reply