gpt4 book ai didi

php - 如何在 Wordpress 中获取一天中的平均发布时间(小时)?

转载 作者:行者123 更新时间:2023-11-29 06:30:02 24 4
gpt4 key购买 nike

我试图构建一个页面(模板)来显示我博客的“写作行为”。为了显示一天中我在哪个小时发布最多的时间,我需要计算“一天的平均发布时间(小时)”,这样我就可以知道“呃我通常在早上发布博客......”

我想到的第一个想法是将所有“时间(小时)”相加,然后除以“总帖子数”,然后转换为 24 小时格式以显示,但似乎我的代码不起作用。

我写的核心代码是这样的:

<?php
$alltimes=$wpdb->get_var($wpdb->prepare("SELECT sum(post_date) FROM $wpdb->posts WHERE post_type = 'post'", $alltimes));
echo '<p>Total post count '.$published_posts.'</p>';
$count_posts = wp_count_posts(); $published_posts = $count_posts->publish;
$averagetime= $alltimes / $published_posts;
echo '<p>Average Time count is '.$averagetime.'</p>';
echo'<p>Average time is '.date('Y-m-d h:i:s',$averagetime).'</p>';
?>

我的错误是年、月、日、小时、秒.. 全部加起来为“$alltimes”,所以当我除时它会变成一场灾难。

也许如果我能得到“post_date”中的“小时”但不是整个“post_date”就可以完成这项工作,但如何做?

感谢您的宝贵时间。

最佳答案

我认为您正在寻找这样的查询。我正在使用 HOUR()DATE() 从日期时间值中提取日期和小时部分:

SELECT HOUR(post_date) hour, COUNT(*) posts FROM wp_posts 
WHERE post_type = 'post' && DATE(post_date) = DATE(NOW())
GROUP BY hour
ORDER BY posts DESC;

这将显示一天中不同时间发布了多少帖子,注意这只会返回 post_date 与当前日期匹配的行。如果您想根据所有帖子获得最多的时间,您只需删除 DATE(post_date) = DATE(NOW()) 条件:

+------+-------+
| hour | posts |
+------+-------+
| 18 | 15 |
| 19 | 12 |
| 21 | 2 |
+------+-------+

如果您只想获得包含最大帖子数的小时的一行,这可行:

SELECT hour, MAX(posts) posts FROM ( 
SELECT HOUR(post_date) hour, COUNT(*) posts FROM wp_posts
WHERE post_type ='post' && DATE(post_date) = DATE(NOW())
GROUP BY hour ORDER BY posts DESC
) v;

或者像这样:

SELECT HOUR(post_date) hour, COUNT(*) posts FROM wp_posts 
WHERE post_type = 'post' && DATE(post_date) = DATE(NOW())
GROUP BY hour
ORDER BY posts DESC
LIMIT 1

引用
Mysql - Date and Time Functions

关于php - 如何在 Wordpress 中获取一天中的平均发布时间(小时)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28512214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com