Most viewed post | WordPress.org

[ad_1]

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.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer