Laimonas Sutkus
Laimonas Sutkus

Reputation: 3617

Wordpress API - post meta field

I am trying to create a post via WP API and I am using python to send http requests. So an example http request body would look like this:

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'
    }
))

And the sending itself looks like this:

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)

Now the good news is that it creates the post.

But it does not set meta fields which makes some of the plugins to have no effect. How do I enforce setting of meta fields via API?

I have heared that I need to expose certain meta fields via PHP code. But how do I do that and most importantly - where do I do that?

EDIT:

I have tried to add this PHP piece of code to functions.php and ideed it showed all meta fields on API GET call, but setting those field was still not possible.

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 );
}

Upvotes: 0

Views: 1026

Answers (1)

Laimonas Sutkus
Laimonas Sutkus

Reputation: 3617

Found an answer.

Simply put this PHP code snippet in your 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);

Upvotes: 1

Related Questions