Last active
October 16, 2023 15:06
-
-
Save nomad411/e3837871843636e2f66ab5867d4edb9f to your computer and use it in GitHub Desktop.
Count Post Views in a WP Custom Field
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
// 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