WordPress统计今日当天发布文章数量

WordPress教程 2250

获取wordpress今天发布文章数量,即是获取0点到24点这个时间段发布的文章数量,之前博客吧分享过wordpress调用当日发布文章数量的代码,实现方法是通过WP_Query类,今天分享的代码则是使用$wpdb对象查询数量库来统计。

把下面的函数放在主题的functions.php文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function get_articles_count_today($post_type ='post') {
    global $wpdb; //全局变量
    $result = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(ID) ".
            "FROM {$wpdb->posts} ".
            "WHERE post_status='publish' ".
                "AND post_type= %s ".
                "AND DATE_FORMAT(post_date_gmt, '%%Y-%%m-%%d') = %s",
            $post_type, date('Y-m-d', time())
        )
    );
	return $result;
}

$post_type 参数是要获取的文章类型

调用代码
1
2
3
4
5
<?php 
if(get_articles_count_today()){
	echo get_articles_count_today(); 
}
?>

默认获取类型为post的文章数量。

如果要获取其它类型的文章数量,可以传递参数,如获取类型为page的数量

1
2
3
4
5
<?php 
if(get_articles_count_today('page')){
	echo get_articles_count_today('page'); 
}
?>

参考:https://wordpress.stackexchange.com/questions/106383/count-posts-or-custom-post-types-from-last-24-hours-or-from-today

精品推荐: