Number of views using WordPress
Display the number of views using WordPress without using a plugin. Add code snippet to file functions.php your topic, then follow the step 1. and step 2. To display the number of views for each individual entry.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function getPostViews($postID){ $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0"; } return $count; } function setPostViews($postID) { $count_key = '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); } } |
Step 1.
Put this snippet below “setPostViews” in single.php inside the loop.
1 2 3 |
<?php setPostViews(get_the_ID()); ?> |
Step 2.
Put this snippet below in your template, where would you like to display the number of views.
1 2 3 |
<?php echo getPostViews(get_the_ID()); ?> |
The number of site views can be displayed in a separate column
To display the number of views in a separate column of your admin panel, you need to add the following code to the functions.php file.
1 2 3 4 5 6 7 8 9 10 11 |
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'] = __('Просмотры'); return $defaults; } function posts_custom_column_views($column_name, $id){ if($column_name === 'post_views'){ echo getPostViews(get_the_ID()); } } |
The code was tested on a test site and everything works. Good luck developing WordPress sites.
/*
- Basic web design course;
- Site layout;
- General course on CMS WordPress and continuation of the course on template development;
- Website development in PHP.