I’m creating a function that displays the most viewed posts and would like to be able to show posts based on how old they are. Modifying the query is not really a problem. But since I can’t pass any arguments to the function I can’t modify the “-30 days” part.
function print_stuff($args) {
add_filter( 'posts_where', 'filter_where');
$posts = new WP_query($args);
remove_filter( 'posts_where', 'filter_where' );
// The loop
}
function filter_where($where = '') {
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
return $where;
}
I guess I could store the value in the DB and then retrieve it, but that would feel ugly. Any ideas?
You can set your own custom query vars in a query, then use that value to set a class variable that you later read in the filter:
Then for your query:
You can store the time range using some global/static/class variable & then retrieve it from there
or use filters (the concept wordpress is built on). Here is an example