1

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

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 );
}
  • Yeah, that's a good idea. 122019_post_views_count this key has to exit right? post_views_count i believe is WordPress default? – Latheesh V M Villa Dec 11 '19 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.