WordPress侧边栏添加信息统计
前言
刚刚写了一篇统计文章字数的文章,现在就教大家如何在侧边栏添加信息统计
教程
在子主题的function.php中添加如下代码
function display_site_stats() {
// 获取统计数据
$total_posts = wp_count_posts()->publish;
$site_uptime = get_site_uptime();
$last_update = get_last_update_time();
$total_word_count = get_total_word_count();
// 输出HTML
$stats = [
'文章数目' => ['value' => $total_posts, 'class' => 'purple'],
'存活天数' => ['value' => $site_uptime, 'class' => 'violet'],
'上次更新' => ['value' => $last_update, 'class' => 'red'],
'文章字数' => ['value' => $total_word_count . ' 万', 'class' => 'red']
];
$output = '<div style="background: #fff; padding: 10px; border-radius: 5px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);">';
foreach ($stats as $text => $data) {
$output .= sprintf(
'<div style="display: flex; align-items: center; margin-bottom: 10px;">
<span style="flex: 1;">%s</span>
<span style="background: %s; color: #fff; padding: 2px 8px; border-radius: 12px; font-size: 0.9em;">%s</span>
</div>',
esc_html($text),
esc_attr(get_badge_color($data['class'])),
esc_html($data['value'])
);
}
$output .= '</div>';
return $output; // 返回输出的HTML
}
function get_badge_color($class) {
switch ($class) {
case 'purple':
return '#9c27b0';
case 'violet':
return '#7e57c2';
case 'red':
return '#e53935';
default:
return '#e0e0e0';
}
}
function get_site_uptime() {
$start_date = new DateTime('2023-04-05'); // 替换为你的网站创建日期
$interval = $start_date->diff(new DateTime());
return $interval->days . '天'; // 直接返回存活的天数
}
function get_last_update_time() {
$last_post = wp_get_recent_posts(['numberposts' => 1])[0];
$time_difference = time() - strtotime($last_post['post_date']);
if ($time_difference < 60) return '刚刚';
if ($time_difference < 3600) return floor($time_difference / 60) . '分钟前';
if ($time_difference < 86400) return floor($time_difference / 3600) . '小时前';
return floor($time_difference / 86400) . '天前';
}
function get_total_word_count() {
$posts = get_posts(['numberposts' => -1]);
$total_word_count = array_sum(array_map(function($post) {
return str_word_count(strip_tags($post->post_content));
}, $posts));
return round($total_word_count / 10000, 2); // 返回万字数
}
// 注册短代码
add_shortcode('xrbk-cbls', 'display_site_stats');
然后在WordPress小工具中添加文本,里面输入[xrbk-cbls]
截图
THE END