WP Post Views for WPEngine - Count Post Views in WordPress without plugin
<?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