Google Web Stories

How to Display Post Views Without A Plugin

Display Post Views Without A Plugin

If you are comfortable with editing code, you can display the number of page views on your website by making a few modifications to your theme files.

1. Access your WordPress admin dashboard by logging in.

2. Go to the “Appearance” section and select “Theme Editor” from the menu.

3. Open the functions.php file within the Theme Editor.

4. Copy the provided code and paste it before the closing tag ?> in the functions.php file.


function anuj_get_post_view() {


    $count = get_post_meta( get_the_ID(), 'post_views_count', true );


    return "$count views";


}


function anuj_set_post_view() {


    $key = 'post_views_count';


    $post_id = get_the_ID();


    $count = (int) get_post_meta( $post_id, $key, true );


    $count++;


    update_post_meta( $post_id, $key, $count );


}


function anuj_posts_column_views( $columns ) {


    $columns['post_views'] = 'Views';


    return $columns;


}


function anuj_posts_custom_column_views( $column ) {


    if ( $column === 'post_views') {


        echo anuj_get_post_view();


    }


}


add_filter( 'manage_posts_columns', 'anuj_posts_column_views' );


add_action( 'manage_posts_custom_column', 'anuj_posts_custom_column_views' );

5. Access the single.php file within the Theme Editor.

6. Copy the provided code and paste it within the while loop of the single.php file. You can use the keyboard shortcut CTRL + F (or Command + F on a Mac) to quickly find the while loop in the file.

anuj_set_post_view();

7. Copy the provided code and paste it in the location where you would like to display the number of posts or page views.

anuj_get_post_view();
Scroll to Top