WordPress.org

Ready to get started?Download WordPress

Forums

Filters and time parameters in sidebae widget (1 post)

  1. sem8seo
    Member
    Posted 1 year ago #

    I am trying to filter tab widget so it is showing 3 random posts not older then 1 month for news category and 3 radnom posts 3 month for other 2 catgeories.

    function getSomePost($category,$postsPerPage=3) {
            global $post;
    
            $args = array(
                'category_name'=>$category,
                'posts_per_page'=>$postsPerPage,
                'post_type'=>'post',
                'post_status'=>'publish',
                'post__not_in'=>array($post->ID),
                'orderby'=>'rand',
            );
    
            switch ($category)
            {
                case 'news':
                    $args['interval'] = '1 MONTH';
                    break;
                case 'analysis':
                    $args['interval'] = '3 MONTH';
                    break;
                case 'reports':
                    $args['interval'] = '3 MONTH';
                    break;
            }
    
            $query = new WP_Query($args);

    I was trying to replace inside switch

    case 'news':
                    $args['interval'] = '1 MONTH';
                    break;

    with

    case 'news':
        // Create a new filtering function that will add our where clause to the query
        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 = new WP_Query( $args );
        remove_filter( 'posts_where', 'filter_where' );
        break;

    and

    case 'analysis':
                        $args['interval'] = '3 MONTH';
                        break;

    with

    case 'analysis':
    // Create a new filtering function that will add our where clause to the query
    function filter_where( $where = '' ) {
        // posts in the last 30 days
        $where .= " AND post_date > '" . date('Y-m-d', strtotime('-90 days')) . "'";
        return $where;
    }
    
    add_filter( 'posts_where', 'filter_where' );
    $query = new WP_Query( $args );
    remove_filter( 'posts_where', 'filter_where' );
    break;

Topic Closed

This topic has been closed to new replies.

About this Topic