How to get the number of visits to an article in 24 hours?

114 views Asked by At

I use this function to save article views

function wpb_set_post_views($postID) {
    $count_key = 'wpb_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
        
        
    }
}
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

is it possible to get views count in 24 hours for example ?

and get most post viewed in 24 hours ?

1

There are 1 answers

0
Oleh Kosarenko On

Try to use a serialized array:

function wpb_set_post_views( $postID ) {
    $count_key = 'wpb_post_views_count';
    $date = date('Ymd');
    $views = get_post_meta($postID, $count_key, true);
    if( !empty($views) AND is_array($views) AND !empty($views[$date]) ){
        $views[$date] = $views[$date] + 1;
    } else {
        $views = array($date => 1);
    }
    update_post_meta($postID, $count_key, $views );
    return $views[$date];
}