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

使用get_the_content()为自定义字段赋值时输出异常,请求帮助

问题解决:自定义字段存入变量值而非字符串

你的代码核心问题是单引号的使用方式错误:PHP中,单引号包裹的内容会被当作纯文本字符串解析,不会解析其中的变量。所以你传入add_post_meta的是字符串'$metadescription',而非变量存储的文章截取内容。

修正后的代码:

$metadescription = wp_trim_words( get_the_content(), 55, '');
add_post_meta($post_id, 'meta_description', $metadescription, true);

额外提示:

  • 确保$post_id是有效的当前文章ID,若在文章循环中,可通过get_the_ID()获取:
    $post_id = get_the_ID();
    $metadescription = wp_trim_words( get_the_content(), 55, '');
    add_post_meta($post_id, 'meta_description', $metadescription, true);
    
  • 如果该自定义字段已存在,add_post_meta的第四个参数true会跳过存储,若需要覆盖已存在的值,可改用update_post_meta:
    update_post_meta($post_id, 'meta_description', $metadescription);
    

内容的提问来源于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 19:45:40