WordPress实现文章编辑 动态年限计算显示方法

方法一:使用短代码

在主题的 functions.php 文件中添加:

function years_since_shortcode($atts) {
    $atts = shortcode_atts(array(
        'year' => 2008,
        'format' => 'full' // 可选:'full' 或 'short'
    ), $atts);
    
    $current_year = date('Y');
    $years = $current_year - $atts['year'];
    
    if ($atts['format'] === 'short') {
        return $years;
    } else {
        return $years . '年';
    }
}
add_shortcode('years_since', 'years_since_shortcode');

使用方法:

  • [years_since year=”2008″] → 显示”16年”(2024年示例)
  • [years_since year=”2008″ format=”short”] → 只显示数字”16″

方法二:直接PHP代码

在模板文件中使用:

<?php
$start_year = 2008;
$current_year = date('Y');
$years = $current_year - $start_year;
echo "从{$start_year}年到现在已经{$years}年了";
?>

方法三:更智能的版本(考虑月份)

如果需要精确到月份的计算:

function calculate_years_since($start_year) {
    $start_date = new DateTime($start_year . '-01-01');
    $current_date = new DateTime();
    $interval = $current_date->diff($start_date);
    return $interval->y;
}

// 使用
$years = calculate_years_since(2008);
echo "从2008年到现在已经" . $years . "年了";

方法四:带缓存的版本(提高性能)

function cached_years_since($start_year) {
    $transient_key = 'years_since_' . $start_year;
    $years = get_transient($transient_key);
    
    if (false === $years) {
        $current_year = date('Y');
        $years = $current_year - $start_year;
        // 缓存24小时
        set_transient($transient_key, $years, DAY_IN_SECONDS);
    }
    
    return $years;
}

// 使用
$years = cached_years_since(2008);

在文章中的使用示例:

从2008年到现在已经[years_since year="2008"]了,我们经历了...

或者

从2008年创立至今,我们已经服务了[years_since year="2008" format="short"]个年头。

优点:

  • 自动更新,无需每年手动修改
  • 代码简洁易用
  • 可以通过短代码在任何文章/页面中使用
  • 性能优化(如果使用缓存版本)
© 版权声明
THE END
喜欢就支持一下吧
点赞13赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容