Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

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:

class WPA69844_where {
    var $days;

    public function __construct(){
        add_action( 'parse_query', array( $this, 'parse_query' ) );
    }

    public function parse_query( $query ) {
        if( isset( $query->query_vars['my_days_var'] ) ):
            $this->days = $query->query_vars['my_days_var'];
            add_filter( 'posts_where', array( $this, 'filter_where' ) );
            add_filter( 'posts_selection', array( $this, 'remove_where' ) );
        endif;
    }

    public function filter_where($where = '') {
        $where .= " AND post_date > '" . date('Y-m-d', strtotime('-' . $this->days . ' days')) . "'";
        return $where;
    }

    public function remove_where() {
        remove_filter( 'posts_where', array( $this, 'filter_where' ) );
    }


}
$wpa69844_where = new WPA69844_where();

Then for your query:

$args = array( 'my_days_var' => 30 );
$posts = new WP_query( $args );
share|improve this answer
    
This is a very elegant solution. Thanks for sharing it. –  Sudar Dec 8 '12 at 16:52
add comment

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

function filter_where($where = '') {
    $time = apply_filters('custom_where_clause', '-30days');
    if(!$time)
        $time = '-30days';

    $where .= " AND post_date > '" . date('Y-m-d', strtotime($time)) . "'";
    return $where;
}

add_filter('custom_where_clause', 'custom_where_clause_logic');
function custom_where_clause_logic($time) {
    // put your logic here
    // make sure you return the value
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.