2

I'm new working with WordPress and I'm playing around with the Advanced Custom Fields plugin. It seems nice but I'd like to know if it's possible to POST a new object (created using ACF) through the WordPress REST API? I'm already using it to GET all my custom objects (thanks to ACF to REST API Plugin).

I'm using WordPress as my backend and NextJS as the frontend so I'd like to create a new HTML form, where the user can input some info and directly create an instance of that object.

If it's not possible, what's the mechanism to save to the database (common MySQL instance) and simulate the same operation I need? I'd like to prevent going through some custom implementation if it's something out there yet (let me know if you need more info about the problem or the data)

EDIT:

After some research, I figured out that I was trying to create the object using the incorrect endpoint.

Now I'm able to create my own object (custom post type) but I'm not able to populate the ACF fields...

I send an standard request:

var data = JSON.stringify({
  "title": "Test00",
  "status": "publish",
  "acf":{
    "customfield1":"Some value..."
  }
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "http://localhost:8000/wp-json/wp/v2/custom");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMCIsImlhdCI6MTU2MDM3NTQxNywibmJmIjoxNTYwMzc1NDE3LCJleHAiOjE1NjA5ODAyMTcsImRhdGEiOnsidXNlciI6eyJpZCI6IjIifX19.BCyrlFm_qD3-9DzCxQ37n4pJYkTasvLaN34NJtFAMC4");
xhr.setRequestHeader("cache-control", "no-cache");

xhr.send(data);

And I receive this:

{
  ...
  "acf":{
    "customfield1":null
  }
}

Is there any way to do it all at once? Should I create the object and then, send the extra info?

2 Answers 2

3

Like the GET request, You can use the POST request as well to store data into the CMS. What you need to do is to pass the authorization headers with the POST API call.
You can get more detail about the authorization mechanism here: https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

Headers:

Authorization:Bearer <token>
Content-Type:application/json

Secondly you can pass the Body data as a RAW json as below:

{
"title":"Sample ACF field demo",
"status": "publish",
"fields": 
    {      
        "text_custom_field_name" : "Text value",
        "checkbox_custom_field_name" : [
                "Option1,",
                "Option2,",
                "Option3"
            ],
        "textarea_custom_field_name" : "This is message field",
        "boolean_custom_field_name" : [
                true
            ]
    }
}

Please let me know if any help needed.

Thanks

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! I'll try it later but in the meantime, just one question, I'm planning to add JWT for Authentication (I'm not a security expert but I've some experience with that) and I've found this tutorial to do so (firxworx.com/blog/wordpress/…) , is it okay to use it without the user being logged in? For instance, creating a new custom object based on a public HTML form or is there any best way to do it?
JWT is a good choice to use. There is a WP plugin available to integrate JWT: wordpress.org/plugins/jwt-authentication-for-wp-rest-api
To use publicly without user login, I would suggest to create a custom endpoint and write down logic to generate the JWT token, And make some custom logic to to use that custom end points. In that way your endpoint and token generation would be secure. Let me know if anything. Thanks!
If I do GET to my endpoint localhost:8000/wp-json/acf/v3/custom , it works but when I try to do a POST directly without even adding any authorization nor any extra data I see: { "code": "rest_no_route", "message": "No se encontró la ruta que coincida con la URL y el método de la petición", "data": { "status": 404 } } do I need to setup something else?
Thanks! I was able to create the object with the custom fields finally! :D
2

TL;DR - ACF now has support for the WP REST API

Hey all, Iain the Product Manager for Advanced Custom Fields here 👋

As part of the ACF 5.11 release we added native support for ACF fields in the WordPress REST API. Read more about that here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.