Display Post Views
Track and display post views.
<?php
function track_post_views($post_id) {
if (!is_single()) return;
if (empty($post_id)) {
global $post;
$post_id = $post->ID;
}
$views = get_post_meta($post_id, 'post_views', true);
if ($views == '') {
$views = 0;
delete_post_meta($post_id, 'post_views');
add_post_meta($post_id, 'post_views', '0');
} else {
$views++;
update_post_meta($post_id, 'post_views', $views);
}
}
add_action('wp_head', 'track_post_views');
function display_post_views() {
global $post;
$views = get_post_meta($post->ID, 'post_views', true);
echo '<p>Views: ' . esc_html($views) . '</p>';
}
add_action('the_content', 'display_post_views');
?>
Post Comment