Show post views without plugin
If you need to show the number of posts or pages on your WordPress site without using a plugin, you can write a simple function and add it to the functions.php
Wordpress
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function simple_post_views( $post_ID ) { global $count_key,$count; $count_key = 'simple_post_views_count'; $count = get_post_meta( $post_ID, $count_key, true ); if ( $count == '' ) { $count = 0; update_post_meta( $post_ID, $count_key, $count ); echo $count . __( ' views', 'your_textdomain' ); } else { if ( is_single() || is_page() ) { $count++; } update_post_meta( $post_ID, $count_key, $count ); echo $count . __( ' views', 'your_textdomain' ); } } |
Now, in order to display the number of views, add this code to the single.php or page.php
<?php simple_post_views( get_the_ID() ); ?>
Bonus
If you also want to show the number of views in the WordPress admin dashboard, use this code:
Wordpress
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// show views for posts add_action('manage_posts_custom_column', 'admin_postviews_column_content'); add_filter('manage_posts_columns', 'admin_postviews_column'); // show views for pages add_action('manage_pages_custom_column', 'admin_postviews_column_content'); add_filter('manage_pages_columns', 'admin_postviews_column'); function admin_postviews_column( $defaults ) { $defaults['viewscolumn'] = 'Views'; return $defaults; } function admin_postviews_column_content() { simple_post_views( get_the_ID() ); } |