I use the Ribbon theme that has a nice tabbed widget showing the most popular and most recent posts. I would like to limit the most popular posts to the last 12 months. I would rather not use a plugin for that but change the code in the theme file. The query is like so:
function mts_popular_tabs( $posts = 5 ) {
$popular = new WP_Query('showposts='. $posts .'&orderby=comment_count&order=desc');
$popular_post_num = 1;
while ($popular->have_posts()) : $popular->the_post();
I tried this snippet:
function filter_where($where = '') {
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-365 days')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where');
It works for the widget but effects other queries, too. I tried to remove the filter, but it didn’t work:
wp_reset_query();
remove_filter('posts_where', 'filter_where');
I tried to rewrite the query like so with no luck:
$today = date('Y-m-d');
$todayminusone = date('Y-m-d', strtotime('-1 year'));
$args = array(
'date_query' => array(
array(
'after' => $today,
'before' => $todayminusone,
),
),
'showposts' => 5,
'orderby' => 'comment_count',
'order' => 'desc'
);
function mts_popular_tabs() {
$popular = new WP_Query($args);
$popular_post_num = 1;
while ($popular->have_posts()) : $popular->the_post();
I’m stuck here. Any help would be appreciated.
Thank you for the help. This is the code I use now:
function mts_popular_tabs( $nr = 5 )
{
$args = array(
'date_query' => array( array( 'after' => '-1 year' ) ),
'posts_per_page' => (int) $nr,
'orderby' => 'comment_count',
'order' => 'DESC'
);
$popular = new WP_Query( $args );
$popular_post_num = 1;
while ($popular->have_posts()) : $popular->the_post();
...
Just as @Rarst suggested, you must have your
$args
defined within your function. You could solve it by using global variables, but we don’t want too many such variables flying around!Check out the PHP docs on the scope of a variable or write your code in a class.
You can also simplify your query. Here’s an example how your function could look like:
This will generate the following SQL query:
if the current date is
'2014-04-06 11:30:26'
.ps: If you want the
posts_where
filter to only affect your instance ofWP_Query
, you should also move it into the function:but you don’t need it in this case.
Hope this helps.