skip to Main Content

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


  1. Here’s how you can nest it to match the structure:

    JSONObject jsonObject = new JSONObject();
    try {
    
        JSONObject acf = new JSONObject();
        acf.put("phone_number", "777-348-4349");
        jsonObject.put("acf", acf);
    
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

    let me know if this worked for you.

    Login or Signup to reply.
  2. 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:

    {
        "acf":
        {
            "field": "Value"
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search