What I’m working in: WordPress with ACF plugin and JavaScript.
What I’m trying to do: create a post and set the title, content, status and some ACF-fields.
What is output: It successfully creates the post, but only sets the title and content. The ACF-fields are blank.
What alternatives I have tried: tried changing ‘acf_fields:’ to ‘fields:’ with no luck.
Question: Am I using the wrong label for ACF-fields? Or is there another way of doing this?
createMarker(latitude, longitude) {
var ourNewPost = {
title: latitude + ", " + longitude,
content: "Coordinates: " + latitude + ", " + longitude,
status: "publish",
acf_fields: {
points_title: "test",
points_latitude: latitude.toString(),
points_longitude: longitude.toString(),
status: 0
},
};
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader("X-WP-Nonce", myData.nonce);
},
url: myData.root_url + "/wp-json/wp/v2/points/",
type: "POST",
data: ourNewPost,
success: (response) => {
console.log(response);
},
error: (response) => {
console.log(response);
},
});
}
Defining my custom post-type:
function points(){
register_post_type('points', array(
'show_in_rest' => true,
'map_meta_cap' => true,
'supports' => array('title', 'editor','custom-fields'),
'show_ui' => true,
'public' => true,
'labels' => array(
'name' => 'Points'
)
));
}
add_action('init', 'points');
2
Answers
You have to call hook when post save and then you can write your code in hook to fill acf field data.
The problem is in your
CreateMarker
function. The object field key for the ACF fields is incorrect – it should simply be:acf
Here’s the documentation link which shows the entire
POST
fields.