Skip to content

Instantly share code, notes, and snippets.

@nutsandbolts
Last active January 22, 2019 15:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nutsandbolts/16e74d427490ef6a7911 to your computer and use it in GitHub Desktop.
Save nutsandbolts/16e74d427490ef6a7911 to your computer and use it in GitHub Desktop.
Calculate and display number of views in Genesis post meta
//* Get post view counts
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 Views";
}
return $count.' Views';
}
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
//* Prevent prefetching from adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
add_action( 'genesis_loop', 'nabm_get_individual_post_count');
function nabm_get_individual_post_count() {
if ( is_single() ) {
setPostViews(get_the_ID());
}
}
//* Add shortcode to display counts in post meta
function nabm_post_views_shortcode() {
echo getPostViews(get_the_ID());
}
add_shortcode( 'post_views', 'nabm_post_views_shortcode' );
@nutsandbolts
Copy link
Author

Enables you to add [post_views] to your entry meta to display the count.

@SamuelKingme
Copy link

Hi Andrea,

Thanks for this excellent code. I am using it on my site and it is working great!

I am would like to know if it possible to change 'Views' to an image or icon (fontawesome or dashicons).
It is currently displayed on my front end as 123 Views but I would like it to display as 123 icon (icon being an icon from fontawesome/dashicons).

Thanks in advance :-)
👍

@mostafa272
Copy link

@nutsandbolts
Hi
I found your code is useful for my work. I try to calculate most popular posts and pages in my plugin. But I have two questions:

  1. why did you use delete_post_meta before adding post meta? If $count value is null, so there is no existing post meta for post_views_count, isn't it?

  2. Why did you remove the action 'adjacent_posts_rel_link_wp_head'? please explain it.

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment