我想在wordpress中显示(今天最热门的帖子),这个列表应该每天自动更新

时间:2015-07-24 15:16:19

标签: php html wordpress

我确实使用了一个功能显示了我网站上最受欢迎的帖子,但问题是此功能一直显示最受欢迎的帖子,我不希望这样。

我想显示(今天最热门的帖子),这个列表应该每天自动更新。

请注意,我不想使用插件

这是在functions.php

<?php //fucntion to sort posts bade in thier views.
$args_views = array(  'posts_per_page'  => 6,  /* get 4 posts, or set -1 for all */
                'orderby'      => 'meta_value',  /* this will look at the meta_key you set below */
                'meta_key'     => 'post_views_count',
                'order'        => 'DESC',
                'post_type'    => 'post',
                'post_status'  => 'publish'
            );
$myposts = get_posts( $args );
foreach( $myposts as $mypost ) {
    /* do things here */
}
?>

这是我在index.php中的查询

<div class="container">
    <?php query_posts($args_views);?>
            <?php while ( have_posts() ) : the_post(); ?>
            <div id="archive-thumbnail" class="thumbnail">
                <div class=" <?php if ( has_catch_that_image() ) { ?>archive-body <?php } ?>">
                  <div id="archive-img"><img class="media-object-sp" src="<?php echo has_catch_that_image(); ?>" alt="..."></div>
                  <h4 id="archive-thumbnail-title" style="color:#337ab7;"><a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a></h4>
                  <p id="archive-thumbnail-excerpt"><?php the_excerpt();?></p>
                  <p class="text-muted"> by: <?php the_author(); ?> | before<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ''; ?></p></div>

            </div>
            <?php endwhile; ?>
</div>

,这是在Snigle.php

    <?php // this is to count the views
 setPostViews(get_the_ID()); ?>

1 个答案:

答案 0 :(得分:0)

您可以设置WordPress CRON作业,以便每天重置发布视图计数。请注意:所有观看次数都将每天删除,您无法收回。

用于设置CRON和重置视图计数的示例代码:

// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'subh_daily_cron_action' ) ) {
    wp_schedule_event( time(), 'daily', 'subh_daily_cron_action' );
}

/**
 * Reset the post views on daily basis.
 */
function subh_reset_postview_counters() {
    $count_key = 'post_views_count';
    $args      = array(
        'numberposts'      => -1,
        'meta_key'         => $count_key,
        'post_type'        => 'post',
        'post_status'      => 'publish',
        'suppress_filters' => true
    );

    $postslist = get_posts( $args );
    foreach ( $postslist as $singlepost ) {
        delete_post_meta( $singlepost->ID, $count_key );
    }
}
add_action( 'subh_daily_cron_action', 'subh_reset_postview_counters' ); // Hook into that action that will fire daily.

将上述代码粘贴到当前主题的functions.php文件中。尽可能尝试使用Child主题(虽然这是可选的)。

有关通过WordPress设置CRON作业的详细信息,请访问:https://codex.wordpress.org/Function_Reference/wp_schedule_event