Last active
September 5, 2015 22:15
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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