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

使用wpapi for nodejs操作WP文章:如何保留短代码追加内容?

解决WPAPI获取WordPress原始文章内容(含短代码)并追加内容的问题

要解决你遇到的短代码丢失问题,核心是获取WordPress存储的原始未渲染内容,而非API默认返回的渲染后HTML。以下是具体实现方法:

1. 获取原始内容(含短代码)

WP REST API默认返回view上下文的内容(已渲染、无短代码),你需要切换到edit上下文来获取原始内容:

// 获取指定ID的文章原始内容
wp.posts().id(你的文章ID)
  .context('edit') // 关键:切换到编辑上下文
  .then(post => {
    // post.content.raw 就是带短代码的原始内容
    const originalRawContent = post.content.raw;
    // 在这里执行追加操作
  })
  .catch(err => console.error('获取失败:', err));

也可以通过_fields参数精准获取原始内容字段,减少返回数据量:

wp.posts().id(你的文章ID)
  ._fields('content.raw')
  .then(post => {
    const originalRawContent = post.content.raw;
  });

2. 追加内容并更新文章

基于原始内容修改后,再提交更新即可完整保留短代码:

const postId = 你的文章ID;
const newContentToAppend = '\n\n这是要追加的新内容,支持[shortcode]短代码[/shortcode]';

wp.posts().id(postId)
  .context('edit')
  .then(post => {
    const updatedContent = post.content.raw + newContentToAppend;
    // 更新文章内容
    return wp.posts().id(postId).update({
      content: updatedContent
    });
  })
  .then(updatedPost => {
    console.log('文章更新成功,短代码已保留');
  })
  .catch(err => console.error('更新失败:', err));

注意事项

  • 权限要求:使用edit上下文需要请求具备文章编辑权限,确保你的WPAPI实例已配置正确的认证方式(比如WordPress应用密码、JWT令牌)。
  • 绝对不要用content.rendered的内容修改后提交,否则短代码会被转换成HTML,丢失原始结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:42:19