How to display post view count by date, week and month?

I am using the below code to display post views. How can I get the data for every day, week and month?

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' );

Topic views post-meta Wordpress

Category Web


As you are doing update_post_meta( $post_id, $key, $count ); for which $key is 'post_views_count', you can't. You are updating the meta key as is.

You could however change how you are saving the meta key. You could add a prefix to the meta key you're using to differentiate the day, week, and month.

example for month:

function gt_set_post_view_by_month() {
    $prefix = date('mY') // 122019
    $key = $prefix . '_post_views_count'; // `122019_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 );
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.