I am trying to use Ajax and jQuery to post data to a custom post type. The title field works as is standard wordpress field but the color field does not. I also tried replacing 'color' with the name of the ACF itself like 'field_5ec63bc5b6fe0' but that also does not work.
$('.submit-color').on('click', function (e) {
e.preventDefault();
var newColor = {
'title': $( '.title' ).val(),
'color': $( '.color' ).val(),
'status': 'private'
}
$.ajax({
url: myData.root_url + '/wp-json/wp/v2/color/',
type: 'POST',
data: newColor,
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', myData.nonce);
}
})
.done(function (data) {
console.log(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
console.warn(jqXHR.responseText);
});
})
I am trying to use Ajax and jQuery to post data to a custom post type. The title field works as is standard wordpress field but the color field does not. I also tried replacing 'color' with the name of the ACF itself like 'field_5ec63bc5b6fe0' but that also does not work.
$('.submit-color').on('click', function (e) {
e.preventDefault();
var newColor = {
'title': $( '.title' ).val(),
'color': $( '.color' ).val(),
'status': 'private'
}
$.ajax({
url: myData.root_url + '/wp-json/wp/v2/color/',
type: 'POST',
data: newColor,
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', myData.nonce);
}
})
.done(function (data) {
console.log(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
console.warn(jqXHR.responseText);
});
})
Share
Improve this question
asked May 21, 2020 at 9:15
user10980228user10980228
1691 silver badge14 bronze badges
1 Answer
Reset to default 2If the custom field's name (i.e. meta key) is correct and the field is enabled for the REST API, then you should be able to update the meta by adding it in the meta
property, which is an array of meta key-value pairs, like so:
var newColor = {
'title': $( '.title' ).val(),
'meta': {
'color': $( '.color' ).val(),
'key2': 'value',
'key3': 'value',
// ...
},
'status': 'private'
}
Update: You can use register_meta()
or register_post_meta()
to enable the meta for the REST API: (without using any 3rd-party plugin)
// First parameter is the post type.
register_post_meta( 'color', 'color', [
'single' => true,
'show_in_rest' => true,
// Other args, if any.
] );
Update 2: Regarding the "ACF to REST" plugin, you should check the documentation here, but from what I could tell:
You'd want to enable the filters here.
Use the endpoint
/wp-json/acf/v3/color
to add or update yourcolor
custom post.Use the
fields
property instead ofmeta
for the default endpoint (/wp-json/wp/v2/color
). So for example, you'd use'fields': { 'color': $( '.color' ).val() }
in your JS.
(You're supposed to find that on your own.. but anyway, I hope it helps and please check the docs for further assistance.)