簡體   English   中英

每小時重置帖子數

[英]Resetting the post count every hour

我目前正在使用此代碼來顯示按觀看次數排序的最受歡迎的帖子,到目前為止效果很好:

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

我想每小時將視圖計數重置為0,但是我不太確定如何處理。 我可以使用下面的代碼,但到目前為止還沒有運氣。 這是正確的方向嗎?

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

任何幫助將不勝感激!

我認為問題可能與您使用get_posts() ...

您正在傳遞meta_key ,但沒有給它提供一個值來與meta_value

嘗試僅從參數中刪除meta_key行。

meta_key應類似於:

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

這將使用color postmeta的字段獲取所有帖子,其中值是red

希望這可以幫助。 我認為您的代碼非常接近。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM