【问题标题】:WP Rest API - Post to ACF field?WP Rest API - 发布到 ACF 字段?
【发布时间】:2022-11-26 18:22:21
【问题描述】:

我正在尝试通过 REST API 从我的 android 应用程序发布到我的自定义 Wordpress 字段。也就是说,当我查看任何 ACF 字段的 JSON 结构时,它们嵌套在“acf”中,如下所示:

{
  "acf": {
    "phone_number": "000-0000"
  }
}

我正在尝试使用以下代码/结构将电话号码发布到端点的 phone_number 字段,但它似乎无法保存?

        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;
    }}

我想这是因为 phone_number 嵌套在“acf”中。我该如何写这一行:

jsonObject.put("phone_number", "777-348-4349");

以便它匹配上面的结构?我似乎无法弄清楚如何将 phone_number 嵌套在 acf 值中。

【问题讨论】:

  • 你能试试我的解决方案吗?

标签: java wordpress advanced-custom-fields wordpress-rest-api


【解决方案1】:

以下是如何嵌套它以匹配结构:

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();
}

如果这对您有用,请告诉我。

【讨论】:

  • 现在试试这个 :) 很快就会回来报告!
  • 刚刚尝试了这个解决方案,我的 Wordpress 后端的 phone_number 字段仍然是空的:/ 这很奇怪,因为当我记录 jsonObject 时,它似乎嵌套正确。
  • 您的 ACF 字段是否“显示在 REST API 中”?请求是否正确验证?用 Postman 发帖有用吗?
【解决方案2】:

this page 上解释了将 ACF 与 REST API 结合使用。把它们加起来:

  • 您至少需要 ACF 5.11 版

  • 您需要为您的字段组启用 REST API

  • 用户端点是/users/{user_id}/users/me(不是/users/loggedinuser/{user_id}

  • JSON 结构如下:

{
    "acf":
    {
        "field": "Value"
    }
}

【讨论】:

    猜你喜欢
    • 2021-10-08
    • 2019-05-04
    • 2017-08-20
    • 2019-10-26
    • 2022-07-23
    • 2019-03-26
    • 2023-03-15
    • 2018-03-23
    • 2017-09-12
    相关资源
    最近更新 更多