WordPress获取本周/今日/24小时内更新的文章数量

前些时在群里聊天,有个朋友在群里问:WordPress怎么获取到今日发布的文章数量,我嫌麻烦没有理会。

今天在做wordpress博客文章统计的时候,自己刚好要用到,于是在网上搜了搜,整理了一下几种文章统计的方式:

获取本周发布的文章数量


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//WordPress获取本周发布的文章数量

function get_week_post_count(){
    $date_query = array(
        array(
            'after'=>'1 week ago'
        )
    );$args = array(
        'post_type' => 'post',
        'post_status'=>'publish',
        'date_query' => $date_query,
        'no_found_rows' => true,
        'suppress_filters' => true,
        'fields'=>'ids',
        'posts_per_page'=>-1
    );
    $query = new WP_Query( $args );
    return $query->post_count;
}

使用方法:

将上面获取本周发布的文章数量代码添加到当前主题的 functions.php


1
<?php echo get_week_post_count()?>

获取今天发布的文章数量


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//WordPress获取今天更新的文章数量

function get_posts_count_from_today($post_type ='post') {
    global $wpdb;

    $numposts = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(ID) ".
            "FROM {$wpdb->posts} ".
            "WHERE post_status='publish' ".
                "AND post_type= {5cc1b29162d549a8071384de182cc9fc6e6a0fd85e7907f22fd9e18cff4269c3}s ".
                "AND DATE_FORMAT(post_date, '{5cc1b29162d549a8071384de182cc9fc6e6a0fd85e7907f22fd9e18cff4269c3}Y-{5cc1b29162d549a8071384de182cc9fc6e6a0fd85e7907f22fd9e18cff4269c3}m-{5cc1b29162d549a8071384de182cc9fc6e6a0fd85e7907f22fd9e18cff4269c3}d') = {5cc1b29162d549a8071384de182cc9fc6e6a0fd85e7907f22fd9e18cff4269c3}s",
            $post_type, date('Y-m-d', time())
        )
    );
    return $numposts;
}

使用方法

将上面获取今天发布的文章数量代码添加到当前主题的 functions.php ,然后在需要调用的地方使用下面的代码即可:


1
<?php echo get_today_post_count()?>

上面代码为获取默认为“post”这个文章类型,如果你要获取其他文章类型,比如 site,可以这样用:


1
<?php echo get_posts_count_from_today('site'); ?>

获取最近24小时发布的文章数量


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//WordPress获取最近24小时发布的文章数量
function get_posts_count_from_last_24h($post_type ='post') {
    global $wpdb;

    $numposts = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(ID) ".
            "FROM {$wpdb->posts} ".
            "WHERE ".
                "post_status='publish' ".
                "AND post_type= {5cc1b29162d549a8071384de182cc9fc6e6a0fd85e7907f22fd9e18cff4269c3}s ".
                "AND post_date> {5cc1b29162d549a8071384de182cc9fc6e6a0fd85e7907f22fd9e18cff4269c3}s",
            $post_type, date('Y-m-d H:i:s', strtotime('-24 hours'))
        )
    );
    return $numposts;
}

使用方法

将上面获取最近24小发布文的章数量代码添加到当前主题的 functions.php ,然后在需要调用的地方使用下面的代码即可:


1
<?php echo get_posts_count_from_last_24h(); ?>

上面代码为获取默认为“post”这个文章类型,如果你要获取其他文章类型,比如 site,可以这样用:


1
<?php echo get_posts_count_from_last_24h('site'); ?>
原文链接:https://xiaohost.com/1525.html,转载请注明出处。
0

评论0

请先