I’m trying to post to my custom WordPress field via the REST API from my android app. That said, when I look at the JSON structure of any ACF fields, they’re nested inside "acf" like so:
{
"acf": {
"phone_number": "000-0000"
}
}
I’m trying to post a phone number to the phone_number field at my endpoint with the following code/structure, but it won’t seem to save?
OkHttpClient client = new OkHttpClient();
String url = "http://myurl.com/wp-json/wp/v2/users/loggedinuser/36";
String bearer = "Bearer ";
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("phone_number", "777-348-4349");
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url(mergeUrl)
.method("POST", body)
.addHeader("Accept-Charset", "application/json")
.addHeader("Authorization", bearer + userToken)
.addHeader("Content-Type", "application/json")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
int responseCode = response.code();
if (responseCode == 200) {
} else {
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}}
I imagine it’s because phone_number is nested inside of "acf". How can I write this line:
jsonObject.put("phone_number", "777-348-4349");
so that it matches the structure above? I can’t seem to figure out how to nest phone_number inside of the acf value.
2
Answers
Here’s how you can nest it to match the structure:
let me know if this worked for you.
Using ACF with the REST API is explained on this page. To sum it up:
You need at least ACF version 5.11
You need to enable the REST API for your field groups
The endpoints for users are
/users/{user_id}
and/users/me
(not/users/loggedinuser/{user_id}
)The JSON structure is the following: