You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress通过函数与短代码实现自动显示临近首个工作日的方法

短代码实现:展示当前/下月首个工作日日期

以下代码可直接追加到WordPress主题的functions.php文件中,和你已有的年份短代码逻辑完全兼容:

function first_workday_shortcode() {
    // 对齐WordPress设置的时区,避免时区偏差
    date_default_timezone_set( wp_timezone_string() );

    // 获取当前基准时间
    $current_year = date('Y');
    $current_month = date('n');
    $today_timestamp = strtotime('today'); // 统一用当日0点做判定基准,避免时分秒干扰

    // 计算当月第一个工作日的时间戳
    $current_month_first_workday = strtotime("first weekday of {$current_year}-{$current_month}-01");

    // 判定逻辑:如果当月首个工作日已过,切换到下个月计算
    if ($current_month_first_workday < $today_timestamp) {
        // 自动处理12月跨年场景,不会出现月份越界问题
        $next_month_base = mktime(0, 0, 0, $current_month, 1, $current_year);
        $next_month_timestamp = strtotime('+1 month', $next_month_base);
        $next_year = date('Y', $next_month_timestamp);
        $next_month_num = date('n', $next_month_timestamp);
        $target_workday_timestamp = strtotime("first weekday of {$next_year}-{$next_month_num}-01");
    } else {
        $target_workday_timestamp = $current_month_first_workday;
    }

    // 格式化输出结果,可按需修改日期格式
    return date('Y年n月j日', $target_workday_timestamp);
}
// 注册短代码,调用格式为 [first_workday]
add_shortcode('first_workday', 'first_workday_shortcode');

关键说明

  • 替换了你之前提到的weekday 英文月份 年份的解析方式,改用固定数字年月的规则,不会因为服务器语言环境、时区问题出现解析错误
  • 完全按照你构想的流程实现逻辑:先算当月首个工作日,比对是否已过当日0点,过了就自动计算下个月的首个工作日
  • 自动处理12月跨年的边界场景,不会出现12月过了首个工作日之后,月份计算越界报错的问题
  • 日期格式可自定义:如果需要输出d-m-Y这类国际格式,只要将最后return里的格式字符串替换为对应格式即可

使用方法

在文章、页面、小工具的文本编辑器里,直接输入短代码[first_workday],即可自动展示对应日期。

判定规则参考:如果当月首个工作日是当月3号,而当前日期已经是4号,页面会自动跳转到下个月的第一个工作日日期;如果当月首个工作日是当月3号,当前日期为1号或2号,则直接展示当月3号的日期。

内容的提问来源于stack exchange,提问作者Sammy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.28 05:24:10