Accessing user Meta data via REST and backbone
I'm writing a plugin to allow users to update information stored in wp_usermeta. I'm trying to use the Backbone JavaScript client with REST. I have the HTML code.
div id="container"Loading.../div
And my JavaScript code
(function( $ ) {
'use strict';
$(function(){
var app ={};
app.pilot = new wp.api.models.User( { id: 1} );
app.pilot.fetch().then(function(){
console.log( app.pilot );
new app.PilotDataView({model: app.pilot});
});
app.PilotDataView = Backbone.View.extend({
el: '#container',
template: _.template("h3Hello %= name % /h3"),
initialize: function(){
this.render();
},
render: function(){
this.$el.html(this.template(this.model.toJSON() ));
return this;
}
});
}) // $(function) close
})( jQuery );
This works great as "name" is stored in wp_users and is correctly filled in the template. However as I want to access meta data. I have added PHP code to expose cellphone in the REST response:
$object_type = 'user';
$meta_args = array(
'type' = 'string',
// Shown in the schema for the meta key.
'description' = 'A meta key associated with a string meta value.',
'single' = true,
// Show in the WP REST API response. Default: false.
'show_in_rest' = true,
);
register_meta( $object_type, 'cellphone', $meta_args );
}
This is also working correctly. However 'cellphone' is returned in the 'meta' property of the 'attributes' property. Backbone does not appear to be be able to access this. So far the only solution I've come up with is to add
app.pilot['attributes'].cellphone = app.pilot['attributes']['meta']['cellphone'];
This copies the 'meta' property to the 'attributes' property and allows Backbone to find it. Is there a better way to access this property? Ultimatelly I want to create a form that allows the user to update this meta info.
My other thought is to create my own my own custom endpoint to handle this? It seams a shame to by-pass the built in features.