How do I update Advanced Custom Fields on Wordpress with node-WPAPI?

533 Views Asked by At

I'm using node-wpapi to interact with my Wordpress site.

I have the Advanced Custom Fields and ACF to REST API plugins installed.

I'm trying to use wpapi to update the value of the property "main_sidebar" for a post. Here is currently working code that gets and logs the contents of "main_sidebar" for post 62542:

const WPAPI = require ('wpapi');


var wpdev = new WPAPI ({
    endpoint: '..../wp-json',
    username: '...',
    password: '...'
});

wpdev.acfAPI = wpdev.registerRoute("acf/v3", "/posts/(?P<id>[\\d]+)/?(?P<field>[\\w\\-\\_]+)?", {
    params: [ 'main_sidebar' ]
});

main();

async function main () {
    let resp = await wpdev.acfAPI().id(62542).field("main_sidebar").get();
    console.log(resp);
    console.log(JSON.stringify(resp));
}

I cannot figure out how to set the value of this property. I don't understand how I'm supposed to interact with it. I tried updating it on the actual post as well, with no luck:

await wpdev.posts().id(...).update({
    data: { "acf": { "main_sidebar": "test value" } }
});

If this can't be done with wpapi for some reason I'm open to doing it some other way. I only need to update this specific property for each post.

Edit:

I believe I may have been trying to update the wrong resource. Here's what I'm trying now:

    let result = await wpdev.posts().id(117925).auth().update({
        data: {
            "acf": {
            "main_sidebar": "test"
            }
        },
        status: 'publish'
    });
    console.log(result);

This doesn't throw an error and "result" is just the post data. It doesn't update the post. Now I'm twice as confused.

1

There are 1 best solutions below

0
On

Figured it out. Here's the working code. You should be able to replace "main_sidebar" with the name of any field set by acf.

    let result = await wpdev.posts().id(117925).auth().update({
        "fields": {
            "main_sidebar": "test"
        },
        status: 'publish'
    });
    console.log(result);