New Begin
New Begin

Reputation: 27

How can I get my number of views for a single post in wordpress?

I'm facing a problem, while I tried to retrieve number of views for a single post by the following code:

<?php $id = get_the_ID(); ?>
<?php $views = get_post_meta($id, 'post_views_count', true); var_dump($views) ?> 

But I got string(0)"" result.

As per my understanding, it means there is no 'post_views_count' column available in my database and so I found looking up my database.

Now, how can I get number of views for a single post?

Best Regards

Upvotes: 0

Views: 1027

Answers (1)

Mirza Areeb Baig
Mirza Areeb Baig

Reputation: 21

even i was facing this problem but this code helped me i hope this helps you. Copy this code in your function.php before the closing tag?>

function gt_get_post_view() {
    $count = get_post_meta( get_the_ID(), 'post_views_count', true );
    return "$count views";
}
function gt_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 gt_posts_column_views( $columns ) {
    $columns['post_views'] = 'Views';
    return $columns;
}
function gt_posts_custom_column_views( $column ) {
    if ( $column === 'post_views') {
        echo gt_get_post_view();
    }
}
add_filter( 'manage_posts_columns', 'gt_posts_column_views' );
add_action( 'manage_posts_custom_column', 'gt_posts_custom_column_views' );

Then copy this code in single.php file in the while loop

<?php gt_set_post_view(); ?>

& now paste this code where you want to show post count

<?= gt_get_post_view(); ?>

Upvotes: 1

Related Questions