繁体   English   中英

Wordpress API - 发布元字段

[英]Wordpress API - post meta field

我试图通过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 );
}

找到答案。

只需将此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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM