简体   繁体   中英

Resetting the post count every hour

I'm currently using this code to display the most popular post sorted by view count which has worked well so far:

 /**
*   Count visits to post.
*/

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

}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

/**
*   Single post count code
*/

function wpb_track_post_views ($post_id) {
    if ( !is_single() ) return;
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;
    }
    wpb_set_post_views($post_id);
}
add_action( 'wp_head', 'wpb_track_post_views');

I would like to reset the view count to 0 on an hourly basis but I'm not too sure how to go about it. I've had a go using the code below but haven't had any luck so far. Is this the right direction to be going in?

/**
 * Reset the post views on hourly basis.
 */


if ( ! wp_next_scheduled( 'daily_cron_action' ) ) {
    wp_schedule_event( time(), 'hourly', 'daily_cron_action' );
}


function reset_postview_counters() {
    $count_key = 'wpb_post_views_count';
    $args      = array(
        'numberposts'      => -1,
        'meta_key'         => $count_key,
        'post_type'        => 'event',
        'suppress_filters' => true
    );

    $postslist = get_posts( $args );
    foreach ( $postslist as $singlepost ) {
        delete_post_meta( $singlepost->ID, $count_key );
    }
}
add_action( 'daily_cron_action', 'reset_postview_counters' );

Any help would be massively appreciated!

I think the issue might be something to do with the way you are using get_posts() ...

You're passing in a meta_key , but not giving it a value to check against with meta_value .

Try just removing the meta_key line from your args.

The meta_key should be used like:

$args = array(
        'numberposts'      => -1,
        'meta_key'         => 'color',
        'meta_value'       => 'red',
        'post_type'        => 'event',
        'suppress_filters' => true
    );

That would grab all the posts with the color postmeta field where the value is red

Hope this helps. Your code is really close I think.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM