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

WordPress插件条件判断问题:优化自定义日期空值显示

修复MyDateTest插件自定义日期格式问题

你的问题核心是空字段直接拼接导致多余斜杠,同时原代码存在语法错误(is_singular("page")缺少闭合括号)。以下是修正后的完整代码,可彻底解决空字段带来的无效格式问题:

<?php
/**
 * Plugin Name: MyDateTest
 * ...
 */
add_filter("the_content", "add_custom_date");

function add_custom_date($content)
{
    // 修正语法错误:补全闭合括号
    if (is_singular("page")) {
        return $content;
    }

    // 单独获取各自定义日期字段值
    $custom_month = get_post_meta(get_the_ID(), "custom_month", true);
    $custom_day = get_post_meta(get_the_ID(), "custom_day", true);
    $custom_year = get_post_meta(get_the_ID(), "custom_year", true);

    // 收集非空的日期片段
    $date_parts = [];
    if (!empty($custom_month)) {
        $date_parts[] = $custom_month;
    }
    if (!empty($custom_day)) {
        $date_parts[] = $custom_day;
    }
    if (!empty($custom_year)) {
        $date_parts[] = $custom_year;
    }

    // 仅当存在有效日期片段时,才添加日期行
    if (!empty($date_parts)) {
        $formatted_date = implode('/', $date_parts);
        $content = "<br/><strong>Date:</strong> " . $formatted_date . $content;
    }

    return $content;
}
?>

关键修改说明:

  1. 修复语法错误:给is_singular("page")补上闭合括号,避免插件运行报错。
  2. 拆分字段获取逻辑:将三个自定义字段的值单独存入变量,便于后续判断和处理。
  3. 过滤空值片段:用empty()逐个判断字段,只将非空值加入日期片段数组。
  4. 动态拼接有效日期:通过implode('/')将非空片段用斜杠连接,自动避免出现多余的斜杠(比如仅填年份时只显示年份,填月+年则显示月/年)。
  5. 空值场景优化:如果三个字段全为空,就不输出任何日期行,避免显示无意义的Date:文本。

修改后无论哪几个字段为空,都能生成格式合规的日期,彻底解决1//1980或/1/1980这类无效格式问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:32:33