A primitive method that allows you to display the number of views of any Wordress site without using plugins for saving to the database (the load increases).
1. A function that will count the number of views of records in the database. Place in your file functions.php:
function custom_set_post_views( $postID ) { $count_key = 'page_views'; $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 ); } }
2. Now let’s create a function that will display the number of views of your post, also add to your functions.php file:
function custom_get_post_views($postID){ $count_key = 'page_views'; $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"; } echo $count; }
3. Place functions on the pages the number of views of which we want to count, for this, for example, open the file single.php (for posts) or page.php (for pages) and add these two functions to it:
custom_set_post_views(get_the_ID());//counts the number of views custom_set_post_views(get_the_ID());//outputs the number of views