WordPress网站底部添加运行时间显示的方法

来自:素雅营销研究院

头像 方知笔记
2025年05月07日 14:35

在WordPress网站底部添加运行时间显示是一个不错的个性化功能,可以让访客了解您的网站已经稳定运行了多久。下面介绍几种实现方法:

方法一:使用代码片段添加到functions.php

  1. 登录WordPress后台
  2. 进入”外观”→”主题编辑器”
  3. 在右侧找到并点击”functions.php”文件
  4. 在文件末尾添加以下代码:
function display_site_runtime() {
$start_date = '2023-01-01'; // 替换为您的网站上线日期
$start_time = strtotime($start_date);
$current_time = time();
$runtime = $current_time - $start_time;

$days = floor($runtime / (60 * 60 * 24));
$hours = floor(($runtime % (60 * 60 * 24)) / (60 * 60));
$minutes = floor(($runtime % (60 * 60)) / 60);
$seconds = $runtime % 60;

echo '<div class="site-runtime">本站已运行: '.$days.'天'.$hours.'小时'.$minutes.'分'.$seconds.'秒</div>';
}
add_action('wp_footer', 'display_site_runtime');

方法二:使用插件实现

  1. 安装并激活”Insert Headers and Footers”插件
  2. 进入”设置”→”Insert Headers and Footers”
  3. 在”Footer”部分添加以下JavaScript代码:
<script>
function show_runtime() {
var start_date = new Date("2023-01-01"); // 替换为您的网站上线日期
var now = new Date();
var runtime = now - start_date;

var days = Math.floor(runtime / (1000 * 60 * 60 * 24));
var hours = Math.floor((runtime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((runtime % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((runtime % (1000 * 60)) / 1000);

document.getElementById("runtime").innerHTML = "本站已运行: " + days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
}
setInterval(show_runtime, 1000);
</script>
<div id="runtime"></div>

自定义样式

您可以通过CSS美化运行时间显示:

.site-runtime {
text-align: center;
font-size: 14px;
color: #666;
padding: 10px 0;
background-color: #f5f5f5;
margin-top: 20px;
}

注意事项

  1. 修改代码前建议备份网站
  2. 确保日期格式正确(YYYY-MM-DD)
  3. 如果使用子主题,请在子主题的functions.php中添加代码
  4. 某些主题可能有自己的页脚钩子,可能需要调整代码

通过以上方法,您就可以在WordPress网站底部添加一个动态更新的运行时间显示了,这不仅能增加网站的专业感,还能向访客展示网站的稳定性。