Limit WordPress Search Results To Certain Post Types

Wordpress

In WordPress version 3.0 they introduced the ability to have custom post types for your WordPress blog.

This means that instead of using categories to separate your different post types you can actually use different custom post types.

The advantage of this is that you can have a different post template for different post types.

For example with this Blog I post about tutorials or code snippets I could have a different post type for each of these and then create a different template for each post type.

But the problem with different post types is the inbuilt search for WordPress. WordPress will search for all the post types and pages, but there may be some post types which you don't want included in the search results, so you need to exclude some post types from the search results.

Copy the follow code snippet into your functions.php file to include the post type in the search results, this will include the type post and page in the search results.

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

Display List Of Custom Post Types

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

<?php query_posts( array( 'post_type' => 'Tutorials', '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(); ?>

If you want this information to be displayed in a post then it's best to create a shortcode out of this snippet you easily display this on your pages.

Advertise here

Comment