I’m missing something somewhere, but I cannot connect the dots. Everything outputs properly except that the query returns everything from the DB, not just posts. Can anyone spot a reason for this behavior?
Having messed around a bit, I know it’s related to add_filter, removing it allows the query to function normally. However, I still don’t know what is causing the unintended behavior.
Solved: I left out a period…I forgot to concatenate the $where parameter passed into my_posts_where(). Gawd. I have been staring at this for 3 hours…
// Filter 'posts where' so we can limit the date range of a custom query
function my_posts_where( $where = '' ) {
// Posts from the last 30 days
// ERROR $where = " AND post_date > '" . date( 'Y-m-d', strtotime( '-30 days' ) ) . "'";
$where .= " AND post_date > '" . date( 'Y-m-d', strtotime( '-30 days' ) ) . "'";
return $where;
}
// Output a list of the most popular entries from the past 7 days
function my_popular_entries() {
// Filter the query
add_filter( 'posts_where', 'my_posts_where' );
$args = array(
'posts_per_page' => 12,
'orderby' => 'meta_value_num',
'meta_key' => 'Views',
'post_type' => 'post',
);
$query = new WP_Query( $args );
remove_filter( 'posts_where', 'my_posts_where' );
// Create the list, assuming we have posts
if ( $query->have_posts() ) :
$html = '<section id="popular-entries" class="widget"><h1 class="widget-title">Popular Entries</h1><ul class="entries-list">';
while ( $query->have_posts() ) : $query->the_post();
$html .= '<li><article class="hentry">';
$html .= '<div class="text"><h1 class="entry-title"><a href="' . get_permalink() . '" rel="bookmark">' . get_the_title() . '</a></h1></div>';
$html .= '</article></li>';
endwhile;
$html .= '</ul></section>';
echo $html;
// Reset the post variable
wp_reset_postdata();
endif;
}