i want function for post visit on each viewand also show count views in post by idin wordpress i want to set post view data with update_post_meta
To track post views and display the view count in WordPress, you can use the following code:
- Add the following code to your theme's
functions.phpfile:
function set_post_views($postID) {
$countKey = 'post_views_count';
$count = get_post_meta($postID, $countKey, true);
if ($count == '') {
$count = 0;
delete_post_meta($postID, $countKey);
add_post_meta($postID, $countKey, '0');
} else {
$count++;
update_post_meta($postID, $countKey, $count);
}
}
// Add the post view increment function to the WordPress 'wp' action hook
add_action('wp', 'track_post_views');
function track_post_views() {
if (is_single()) {
set_post_views(get_the_ID());
}
}
function get_post_views($postID) {
$countKey = 'post_views_count';
$count = get_post_meta($postID, $countKey, true);
if ($count == '') {
delete_post_meta($postID, $countKey);
add_post_meta($postID, $countKey, '0');
return "0";
}
return $count;
}
- To display the view count in your post template, use the
get_post_views()function:
<?php echo get_post_views(get_the_ID()); ?> Views
This code will increment the view count whenever a post is visited, and you can display the count using the get_post_views() function by passing the post ID as a parameter
原文地址: http://www.cveoy.top/t/topic/iVOP 著作权归作者所有。请勿转载和采集!