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

使用WordPress REST API发布文章无法设置Meta描述,求排查

WordPress REST API 设置Meta描述失败的问题排查与修复

你的代码存在两个核心问题:

  1. 元数据字段位置错误
    你把meta嵌套在data字段里,但WordPress REST API要求meta是请求数据的顶级键,而非嵌套结构。

  2. 自定义元键未注册
    WordPress默认不会将自定义元数据(比如你用的description、keywords)暴露给REST API,必须先在WordPress端注册这些元键,允许通过API进行读写操作。


第一步:修正Python请求代码

把meta从data里移出来,作为顶级字段放在请求数据中:

wp_api_url = "https://xxxxx.com/wp-json/wp/v2/posts"
wp_auth_token = "xxxxxxx"

import requests
meta = {
    "description": "test description",
    "keywords": "test keywords",
    "tags": "test Tag"
}

data = {
    "title": conttitle,
    "content": contcontent,
    "status": "publish",
    "meta": meta  # 直接作为顶级键
}

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {wp_auth_token}",
}
response = requests.post(wp_api_url, headers=headers, json=data)

第二步:在WordPress端注册自定义元键

在你的WordPress主题的functions.php文件,或者自定义插件中添加以下PHP代码,注册需要的元键并开启API访问权限:

// 注册自定义元键,允许通过REST API读写
add_action('rest_api_init', function () {
    // 注册description元键
    register_rest_field('post', 'description', array(
        'get_callback' => function ($object) {
            return get_post_meta($object['id'], 'description', true);
        },
        'update_callback' => function ($value, $object) {
            return update_post_meta($object->ID, 'description', $value);
        },
        'schema' => array(
            'description' => '文章的Meta描述',
            'type' => 'string',
        ),
    ));

    // 注册keywords元键
    register_rest_field('post', 'keywords', array(
        'get_callback' => function ($object) {
            return get_post_meta($object['id'], 'keywords', true);
        },
        'update_callback' => function ($value, $object) {
            return update_post_meta($object->ID, 'keywords', $value);
        },
        'schema' => array(
            'description' => '文章的Meta关键词',
            'type' => 'string',
        ),
    ));

    // 注册tags元键
    register_rest_field('post', 'tags', array(
        'get_callback' => function ($object) {
            return get_post_meta($object['id'], 'tags', true);
        },
        'update_callback' => function ($value, $object) {
            return update_post_meta($object->ID, 'tags', $value);
        },
        'schema' => array(
            'description' => '文章的自定义标签',
            'type' => 'string',
        ),
    ));
});

补充说明

  • 如果你的元键是某个SEO插件(比如Yoast SEO)提供的,需要使用插件对应的元键名,比如Yoast的Meta描述元键是_yoast_wpseo_metadesc,这时候你需要替换成对应的键名,部分插件可能有专属API接口,无需手动注册。
  • 确保你的Bearer令牌拥有edit_posts权限,否则无法修改文章元数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:02:55