Created
January 24, 2014 18:02
-
-
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.
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
/** | |
* 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> Views<span class='assistive-text'>No views</span></span> "; | |
} | |
return "<span title='" . esc_attr( $count ) . " Views'><i class='fa fa-eye'></i> " . esc_attr( $count ) . "<span class='assistive-text'>" . esc_attr( $count ) . " views</span></span> "; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment