jrobinsonc
9/25/2014 - 12:04 AM

Wordpress helper: Post views - Set and get the number of views/hits of a post.

Wordpress helper: Post views - Set and get the number of views/hits of a post.

<?php

class Posts_views
{
    public static $key = 'post_views_count';

    public static function set($post_id)
    {
        $count = intval(get_post_meta($post_id, self::$key, TRUE));

        update_post_meta($post_id, self::$key, ++$count);
    }

    public static function get($post_id)
    {
        return intval(get_post_meta($post_id, self::$key, TRUE));
    }
}
<?php

#####################################################
# Example to show most visited posts.
#####################################################

$custom_query = new WP_query(array(
    'meta_key' => Posts_views::$key,
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
));
?>

<?php if ($custom_query->have_posts()) : ?>
    <?php while ($custom_query->have_posts()) : $custom_query->the_post(); ?>

    <p>
        <a href="<?php the_permalink() ?>"><?php the_title() ?></a>
    </p>

    <?php endwhile; ?>
<?php endif; ?>

<?php 
wp_reset_query();
wp_reset_postdata();