Showing posts between a certain date range Showing posts between a certain date range wordpress wordpress

Showing posts between a certain date range


You can make it dynamic if you resort to global variables.(Not ideal, but hey, I haven't found a cleaner way...)

First define a global variable for the date

$GLOBALS['start_date'] = '2011-07-31';

then add your filter

add_filter( 'posts_where', 'filter_where' ); function filter_where( $date, $where = '' ) {    // posts later than dynamic date    $where .= " AND post_date >= '" . date('Y-m-d H:i:s', strtotime($GLOBALS['start_date'])) . "'";    return $where;}

Then remove the filter if you just want to run that for a single query.


This should do the trick to grab posts in the last 30 days. Beware, however, that this code, placed in your functions.php file, or in a plugin will filter your posts EVERYWHERE. If you only want it to filter on some pages, either wrap it in conditional tags, or use it on a template page:

<?php  function filter_where($where = '') {    // Posts in the last 30 days    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";    return $where;  }add_filter('posts_where', 'filter_where');query_posts($query_string);?>

I stole this code directly from: http://wordpress.org/support/topic/show-the-posts-published-before-a-specific-date?replies=2#post-1066144, where there is a bigger discussion of this issue and there are more examples if this doesn't get exactly what you wanted.


<?php// Show post from a theme option where posts_month is the month 1-12 and posts_year is the year (4 dig)$month = get_option( 'posts_month' );$year = get_option( 'posts_year' );$query = new WP_Query( 'year=' . $year . '&monthnum=' . $month );