• Resolved GPWeM

    (@ligend)


    I created custom functions to have grids of blog posts based on categories, top rated, etc.

    I would also need one for the most viewed/read/opened.

    I’ve been using the plugin for a while and so I have a history that I wouldn’t want to lose.

    Is there a way to recover a parameter, a meta field of the article where there is the WP Statistics data of the visits of each individual article in order to then create a query on that?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Mostafa Soufi

    (@mostafas1990)

    Hello,

    Thank you for raising this topic. It’s important to note that WP Statistics does not store data in wp_postmeta. Instead, all data is kept in WP Statistics’ own tables.

    To generate a list of posts based on views, it’s better to use data directly from WP Statistics. Here’s a suggested approach

    global $wpdb;
    
    $getPopularPosts = get_transient('wp_statistics_popular_article_lifespan');
    $tablePages = \WP_STATISTICS\DB::table('pages');
    
    if (false === $getPopularPosts || empty($getPopularPosts)) {
        $sql = "SELECT {$wpdb->posts}.post_title, {$wpdb->prefix}posts.post_author, {$tablePages}.* 
                FROM {$wpdb->posts} 
                LEFT JOIN ( SELECT {$tablePages}.id, SUM({$tablePages}.count) AS visit 
                            FROM {$tablePages} 
                            GROUP BY {$tablePages}.id ) {$tablePages} 
                ON {$wpdb->prefix}posts.ID = {$tablePages}.id 
                WHERE {$wpdb->posts}.post_type = 'article' 
                AND {$wpdb->posts}.post_status = 'publish' 
                AND {$tablePages}.date >= ( CURDATE() - INTERVAL 30 DAY ) 
                AND {$tablePages}.id IS NOT NULL 
                ORDER BY {$tablePages}.visit DESC 
                LIMIT 0, 20";
        
        $getPopularPosts = $wpdb->get_results($sql);
    
        if (is_array($getPopularPosts) && count($getPopularPosts) > 0) {
            set_transient('wp_statistics_popular_article_lifespan', $getPopularPosts, $cache_lifespan * HOUR_IN_SECONDS);
        }
    }
    
    // Note: This code is untested and might require adjustments.

    I haven’t tested this code, but it should serve as a good starting point.

    Thread Starter GPWeM

    (@ligend)

    Thanks!

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Most viewed post’ is closed to new replies.