Sunday, 8 September 2013

Wordpress Tip: Limit Search Results to Specific 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 wpshock_search_filter( $query ) {
    if ( $query->is_search ) {
        $query->set( 'post_type', array('post','page') );
    }
    return $query;
}
add_filter('pre_get_posts','wpshock_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 books and wanted this post type to be included in the search results you would alter the code like this example below.

array('post','page', 'books')

Wordpress: Completely exclude Sticky posts from the Loop

When you are displaying most recent posts in a tab, you do not want the sticky posts to stay sticky. If you do not remove the sticky feature, the recent posts area would be useless as all your sticky posts will crowd this area. This is where query_posts feature comes in handy.

To do this you will need to change your loop to something like this:

<?php
$args = array(
'posts_per_page' => 10,
'ignore_sticky_posts' => 1
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
?>


This code ignores that a post is sticky and shows the posts in the normal order. Using this code your sticky posts will appear in the loop, however they will not be placed on the top.

Completely exclude Sticky posts from the Loop


If you are using sticky posts in a slider, then sometimes you might want to completely exclude your sticky posts from the loop. All what you have to do is edit your custom loop to match with this:

<?php
$the_query = new WP_Query( array( 'post__not_in' => get_option( 'sticky_posts' ) ) );
if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
?>