Filtering the results of WordPress Query

 

WordPress is a very powerful web site right out of the box.  you can find a host, download and install Worpress in 5 minutes and then load a theme to get your basic structure up and running.  After developing the look and feel, there are often times when you need to dig a bit deeper to get the exact results you want displaying on your pages.  Here is a situation I came across recently that was related to custom post types.

Let’s start from the solution shown in my previous example that defined the $paged global variable that we will use in our query filter:

[info]

global $paged;
if( get_query_var( 'paged' ) )
$my_page = get_query_var( 'paged' );
else {
if( get_query_var( 'page' ) )
$my_page = get_query_var( 'page' );
else
$my_page = 1;
set_query_var( 'paged', $my_page );
$paged = $my_page;
}

[/info]

So this piece of code before my query fixed the issue where my paging wasn’t working. However, when dealing with custom posts, I will get all posts from all times as the WordPress archiving does not deal with the custom post types. These are typical in many themes where you have Testimonials, Portfolios, etc. They complicate things a bit but here is a way to clean up your list of posts.

In this particular case, my client wanted to only see the past 30 days of posts. We ended up using the Testimonial post type, even though these were not testimonials. No matter, let’s filter the posts so that only 30 days worth show on the home page.

First, the function to create the filter to only go 30 days back from today:

[info]
function filter_where( $where = '' ) {
// posts 0 to 30 days old
$where .= " AND post_date >= '" . date('Y-m-d', strtotime('-30 days')) . "'" . " AND post_date <= '" . date('Y-m-d', strtotime('-0 days')) . "'";
return $where; }
add_filter( 'posts_where', 'filter_where' );
[/info]

Now, we put it all together in our WP_query along with our previous paged variable so our paging still works after the filter:
[info]
$options = array('showposts'=> 4, 'post_type'=> testi, $query_string, 'paged'=> $my_page);

$wp_query = new WP_Query( $options );
[/info]

Now, we are done with the filter so we take it off.
[info]
remove_filter( 'posts_where', 'filter_where' );
[/info]

Hopefully, you now see your posts from only the last 30 days. the wp query is a powerful way to filter your results on the fly and especially useful when dealing with custom post types.

Newsletter Updates

Enter your email address below and subscribe to our newsletter