Wordpress API - 发布元字段

问题描述 投票:0回答:1

我正在尝试通过 WP API 创建帖子,并且使用 python 发送 http 请求。因此,http 请求正文示例如下所示:

body = json.dumps(dict(
    slug='test',
    status='publish',
    title='test',
    excerpt='test',
    content='test',
    author=1,
    comment_status='open',
    ping_status='open',
    categories=[1],
    meta={
        '_links_to': 'https://google.com',
        '_knawatfibu_url': 'https://some-image.jpg'
    }
))

发送本身如下所示:

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Basic ' + base64.b64encode(f'{settings.WP_LOGIN}:{settings.WP_PASS}'.encode()).decode()
}

response = requests.post(settings.WP_HOST + '/wp-json/wp/v2/posts', json=data, headers=headers)

现在好消息是它创建了该帖子。

但是它没有设置元字段,这使得一些插件不起作用。如何通过 API 强制设置元字段?

我听说我需要通过 PHP 代码公开某些元字段。但我该怎么做,最重要的是 - 我在哪里做?

编辑:

我尝试将这段 PHP 代码添加到 functions.php 并认为它显示了 API GET 调用上的所有元字段,但仍然无法设置这些字段。

add_action( 'rest_api_init', 'create_api_posts_meta_field' );
function create_api_posts_meta_field() {
    // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
    register_rest_field( 'post', 'meta', array(
        'get_callback' => 'get_post_meta_for_api',
        'schema' => null,
        )
    );
}
function get_post_meta_for_api( $object ) {
    //get the id of the post object array
    $post_id = $object['id'];

    //return the post meta
    return get_post_meta( $post_id );
}
python php wordpress
1个回答
1
投票

找到答案。

只需将此 PHP 代码片段放入您的 functions.php:

add_action("rest_insert_post", function ($post, $request, $creating) {
    $metas = $request->get_param("meta");

    if (is_array($metas)) {

        foreach ($metas as $name => $value) {
            update_post_meta($post->ID, $name, $value);
        }

    }
}, 10, 3);
© www.soinside.com 2019 - 2024. All rights reserved.