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

自定义字段值为空,请问以下WordPress代码存在什么问题?

问题原因与修复方案

核心问题

你的代码存在两个关键问题导致自定义字段值为空:

  1. get_the_content()无法正确获取内容:wp_insert_post钩子触发时,全局$post对象可能还未完全初始化,且当前上下文不在循环内,get_the_content()会返回空值。
  2. 依赖全局$post不可靠:钩子已经传入$post_id,直接调用全局对象容易出现上下文不匹配的问题。

修复后的代码

function add_custom_fields($post_id) {
    // 跳过自动保存和修订版本,避免重复执行
    if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
        return;
    }

    // 直接从数据库读取内容,不依赖全局对象或循环上下文
    $post_content = get_post_field('post_content', $post_id);
    $metadescription = wp_trim_words($post_content, 55);

    // 用update_post_meta替代add_post_meta,自动处理「新增/更新」逻辑
    update_post_meta($post_id, 'meta_description', $metadescription);
}
add_action('wp_insert_post', 'add_custom_fields');

额外说明

  • 增加自动保存和修订版本判断,避免草稿或自动保存时重复生成字段值。
  • get_post_field直接从数据库拉取内容,比get_the_content更稳定,无需依赖循环环境。
  • update_post_meta会自动处理字段存在时更新、不存在时新增的逻辑,比add_post_meta(第四个参数为true时字段已存在则不写入)更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:10:27