1

I am trying to create taxonomy elements (the taxonomies are already registered) from the front end using the REST Api v2. I am able to do so except not able to save the meta fields from the taxonomies.


I have a registered taxonomy ("place") and I am trying to create elements for it using the Rest Api.

The taxonomy has a term meta ("my_meta"). I am able to get the information from the taxonomy:

add_action( 'rest_api_init', 'slug_register_meta' );
function slug_register_meta() {
    register_rest_field( 'place',
        'meta', 
        array(
            'get_callback'    => 'slug_get_meta',
            'update_callback' => null,
            'schema'          => null,
        )
    );
}
function slug_get_meta( $object, $field_name, $request ) {
    return get_term_meta( $object[ 'id' ] );
}

which lets me get the information when I access: /wp-json/wp/v2/place/53

{
    "id": 53,
    "count": 0,
    ...
    "taxonomy": "place",
    "meta": {
        "my_meta": [
            "the meta value"
        ]
    },
    ...
}

I can register a new taxonomy element through JavaScript:

var place_new = new wp.api.models.Place({
    name: 'the name',// works
    description: 'the description',// works

    my_meta: 'test1',// doesn't work

    fields: {// doesn't work
        my_meta: 'test3'
    },

    meta: {// doesn't work
        my_meta: 'test2'
    }

    });

place_new.save();

The problem is the my_meta value won't save, I am not sure how to refer to it or if there is some PHP I am missing.

2

I think you need an update_callback in register_rest_field(). Please note that I haven't tested this.

add_action( 'rest_api_init', 'slug_register_meta' );
function slug_register_meta() {
    register_rest_field( 'place',
        'meta', 
        array(
            'get_callback'    => 'slug_get_meta',
            'update_callback' => 'slug_update_meta',
            'schema'          => null,
        )
    );
}
function slug_get_meta( $object, $field_name, $request ) {
    return get_term_meta( $object[ 'id' ] );
}
function slug_update_meta($value, $object, $field_name){
    // please note: make sure that $object is indeed and object or array
    return update_post_meta($object['id'], $field_name, $value);
}
0

You should pass your meta value as an array to your meta key.

var place_new = new wp.api.models.Place({
    name: 'the name',// works
    description: 'the description',// works

    meta: {
        "my_meta": [
            "new_meta_value"
        ]
    }

});
  • Thanks, but it is not working. – Alvaro Dec 30 '16 at 13:33
  • I've updated it, I'm on mobile now and would confirm once I'm at my desk – Tunji Dec 30 '16 at 13:35
  • The edit is giving a JavaScript error "Unexpected token .", the dot is not accepted. – Alvaro Dec 30 '16 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.