Sree Sree - 2 years ago 79
PHP Question

WordPress Custom Post Type not showing in Search Results

I have an issue with custom post types(Quiz) & search in WordPress. Custom post types are not showing in my search result page. Only the default post content is showing in my search result.

Following are the codes I used

function create_posttype() {

register_post_type( 'compassquiz',
'labels' => array(
'name' => __( 'Compass Quiz' ),
'singular_name' => __( 'Compass Quiz' )
'taxonomies' => array('post_tag'),
'public' => true,
'publicly_queryable' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'free-quiz-bank-exam'),
'query_var' => true,
'exclude_from_search' => false,

add_action( 'init', 'create_posttype' );

Additional code in functions.php

//Read Custom Post types in Search
function filter_search($query) {
if ($query->is_search) {
$query->set('post_type', array('post', 'compassquiz'));
return $query;
add_filter('pre_get_posts', 'filter_search');


if ( have_posts() ) : ?>
<header class="page-header">
<h1 class="page-title">
<?php printf( esc_html__( 'Search Results for: %s', 'compass' ), '<span>' . get_search_query() . '</span>' ); ?>

while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', 'search' );
else :
get_template_part( 'template-parts/content', 'none' );


<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>

<div class="entry-summary">
echo substr(get_the_excerpt(), 0,150) . '...';
echo ('<br><a href="' .get_permalink() . '" class="moretag">Read More &raquo;</a>');
</div><!-- .entry-summary -->
</article><!-- #post-## -->

I have tried lots of code found in WP Fourm & also in other stackoverflow questions. But couldn't find a solution that actually work.

Answer Source

Add this code in search form. set custom post type in hidden field value.

<input type="hidden" name="post_type" value="post type name" />

multiple custom post type search form

<input type="hidden" name="post_type" value="posttype1, posttype2, posttype3" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download