Skip to content

Instantly share code, notes, and snippets.

@nomad411
Last active October 16, 2023 15:06
Show Gist options
  • Save nomad411/e3837871843636e2f66ab5867d4edb9f to your computer and use it in GitHub Desktop.
Save nomad411/e3837871843636e2f66ab5867d4edb9f to your computer and use it in GitHub Desktop.
Count Post Views in a WP Custom Field
// Function to increment view count
//
// Use the following shortcode to display it in Beaver Builder:
//
// [wpbb post:custom_field key='my_post_views_count']
//
// Insert the code below in your child theme's functions.php file
function my_post_views() {
if (is_single()) { // Only run on single post pages
global $post;
$postID = $post->ID;
$count_key = 'my_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);
}
}
}
add_action('wp_head', 'my_post_views');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment