How To Limit WordPress Search Results to Custom Post Types

This short tutorial will show you how to limit WordPress search results to specific post types when creating WordPress sites that have multiple custom post types added. To acheive this functionality we will use the WordPress pre_get_posts filter to hook into the default WordPress search query.

Add this code below to your themes functions.php to limit your search query to the post types of Post and Page only.

function haloseeker_search_filter($query) {
    if ( $query->is_search ) {
        $query->set( 'post_type', array('post','page') );
    }
    return $query;
}
add_filter('pre_get_posts','haloseeker_search_filter');

The important part of the code above where you an add or remove post types is below.

array('post','page')

If for example you created a custom WordPress post type with the name of ABCXYZ and wanted this post type to be included in the search results you would alter the code like this example below.

array('post','page', 'ABCXYZ')

Here is an example:

function haloseeker_search_filter($query) {
  if ($query->is_search) {
    // Insert the specific post type you want to search,such as: ABCXYZ
    $query->set('post_type', 'ABCXYZ');
  }
  return $query;
}
// This filter will jump into the loop and arrange our results before they're returned
add_filter('pre_get_posts','haloseeker_search_filter');

Display List Of Custom Post Types

If you want to see all the custom post types on your blog then you can display a list of these custom post types by using the following code snippet.

<?php query_posts( array( 'post_type' => 'ABCXYZ', 'showposts' => 10 ) );
                        if ( have_posts() ) : while ( have_posts() ) : the_post();
                        ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; wp_reset_query(); ?>

Hope this tutorial is useful for you.!

Leave a Reply

avatar
  Subscribe  
Notify of