Last active
October 31, 2017 23:24
-
-
Save kLOsk/2b0123c2fca5538eb3f6ab8856411301 to your computer and use it in GitHub Desktop.
WP Post Views for WPEngine - Count Post Views in WordPress without plugin
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 | |
if ( ! defined("POST_VIEWS_KEY") ) { | |
define("POST_VIEWS_KEY", "post_views_count"); | |
} | |
// function to display number of posts. | |
function get_post_views( $post_id ){ | |
$count = get_post_meta($post_id, POST_VIEWS_KEY, true); | |
if($count==''){ | |
delete_post_meta($post_id, POST_VIEWS_KEY); | |
add_post_meta($post_id, POST_VIEWS_KEY, '0'); | |
return 0; | |
} | |
return $count; | |
} | |
// function to count views. | |
function update_post_views( $post_id ) { | |
$count = get_post_views( $post_id ); | |
$count++; | |
update_post_meta( $post_id, POST_VIEWS_KEY, $count ); | |
} | |
// Add it to a column in WP-Admin | |
add_filter('manage_posts_columns', 'posts_column_views'); | |
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2); | |
function posts_column_views($defaults){ | |
$defaults['post_views'] = __('Views'); | |
return $defaults; | |
} | |
function posts_custom_column_views($column_name, $id){ | |
if($column_name === 'post_views'){ | |
echo get_post_views(get_the_ID()) . __("Views"); | |
} | |
} | |
?> | |
<?php | |
//usage | |
// To update view count: | |
update_post_views( $post->ID ); | |
// To display view count: | |
$views = get_post_views( $post->ID ); | |
printf( _n ( "%d View", "%d Views", $views), $views ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment