Skip to content

Instantly share code, notes, and snippets.

@JonMasterson
Created January 24, 2014 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonMasterson/8602633 to your computer and use it in GitHub Desktop.
Save JonMasterson/8602633 to your computer and use it in GitHub Desktop.
Display the number of post views on single posts (uses font awesome), just like Dribbble.com.
/**
* Save number of views to post meta.
*/
function sh_set_post_views($postID) {
$count_key = 'sh_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 );
}
}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
/**
* Track the post views
*/
function sh_track_post_views( $post_id ) {
if ( !is_single() ) return;
if ( empty ( $post_id ) ) {
global $post;
$post_id = $post->ID;
}
sh_set_post_views( $post_id );
}
add_action( 'wp_head', 'sh_track_post_views' );
/**
* Retrieve the post views
*/
function sh_get_post_views( $postID ){
$count_key = 'sh_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 "<span title='No Views'><i class='fa fa-eye-slash'></i>&nbsp;Views<span class='assistive-text'>No views</span></span>&nbsp;&nbsp; ";
}
return "<span title='" . esc_attr( $count ) . " Views'><i class='fa fa-eye'></i>&nbsp;" . esc_attr( $count ) . "<span class='assistive-text'>" . esc_attr( $count ) . " views</span></span>&nbsp;&nbsp; ";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment