WordPress

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.

Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

Your email address will not be published. Required fields are marked *