Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Last active September 5, 2015 22:15
Show Gist options
  • Save jrobinsonc/340cd5d2522c141c7aca to your computer and use it in GitHub Desktop.
Save jrobinsonc/340cd5d2522c141c7aca to your computer and use it in GitHub Desktop.
Wordpress helper: Post views - Set and get the number of views/hits of a post.
<?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();
<?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));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment