• Resolved DAM

    (@damland)


    Hello,

    how can I sort the posts by most viewed in the last month?

    I’m currently using this to sort them alphabetically:

    function custom_orderby( $query_args ) {
    $query_args[ ‘orderby’ ] = array( ‘title’ => ‘DESC’, ‘menu_order’ => ‘ASC’ );
    return $query_args;
    }
    add_filter( ‘job_manager_get_listings_args’, ‘custom_orderby’, 99 );

    Thank You (y)

    https://www.ads-software.com/plugins/wordpress-popular-posts/

Viewing 1 replies (of 1 total)
  • Plugin Author Hector Cabrera

    (@hcabrera)

    Hi there!

    Based on something I played with a long time ago, here’s a revised version that should do what you need:

    add_action( 'pre_get_posts', 'sort_by_most_viewed' );
    
    function sort_by_most_viewed( $query ){
        global $wp_query;
    
        // Run this only on the front-end, leave the admin side alone
        if ( !is_admin() && $query->is_main_query() ) {
    
            // Ignore sticky posts
            $query->set( 'ignore_sticky_posts', true );
    
            add_filter( 'posts_fields', 'wpp_query_fields' );
            add_filter( 'posts_join', 'wpp_query_join' );
            add_filter( 'posts_where' , 'wpp_query_where' );
            add_filter( 'posts_groupby', 'wpp_query_group_by' );
            add_filter( 'posts_orderby', 'wpp_query_order_by' );
    
        }
    
    }
    
    function wpp_query_fields( $fields ){
        global $wpdb;
    
        $fields .= ", SUM({$wpdb->prefix}popularpostsdata.pageviews) AS pageviews";
    
        return $fields;
    }
    
    function wpp_query_join( $join ){
        global $wpdb;
    
        $join .= " LEFT JOIN {$wpdb->prefix}popularpostssummary ON " . $wpdb->posts . ".ID = {$wpdb->prefix}popularpostssummary.postid ";
    
        return $join;
    }
    
    function wpp_query_where( $where ){
        global $wpdb;
    
        $now = current_time('mysql');
        $where .= " AND {$wpdb->prefix}popularpostssummary.last_viewed > DATE_SUB('{$now}', INTERVAL 1 MONTH) ";
    
        return $where;
    }
    
    function wpp_query_group_by( $groupby ){
        global $wpdb;
    
        $groupby = "{$wpdb->prefix}popularpostssummary.postid";
    
        return $groupby;
    }
    
    function wpp_query_order_by( $orderby ){
        return "pageviews DESC";
    }

    I didn’t test this, though. Give it a try and let me know how it goes, alright?

Viewing 1 replies (of 1 total)
  • The topic ‘sort post by monthly views’ is closed to new replies.