Search code examples
javascriptwordpressadvanced-custom-fieldswordpress-gutenberg

get/set value of the ACF field by ACF JavaScript API, in a custom block, on the post editing page


I made a custom gutenberg block using the AdvancedCustomFields PRO plugin. This block has a gallery field. I need to make a button that fills the gallery field with certain photos. I render button using a new custom field type, but how to change the value of another field in the same block?

Function acf.findFields (args) in the ACF JavaScript API works well with fields that are attached to the page, but how I can access the field in a specific custom block?


Solution

  • I found solution Append this script to admin panel This code adds a button for the ACF gallery field that fill the gallery with a predefined data.

    (function($){
        setInterval(function() {
            let fields = acf.getFields({type:"gallery"});
            for (let field of fields) {
                if (!field.dasupdated) {
                    field.dasupdated = true;
                    let control = $("<div><button class='button'>Append Attachment</button></div>");
                    control.find("button").click(()=>{
                        field.appendAttachment({attributes:{
                            id: 56060, 
                            url: "http://site.url/image.jpg"
                        }});
                    });
                    $(field.$el[0]).find(".acf-gallery-main .acf-gallery-toolbar").append(control);
                }
            }
        }, 1000);
    })(jQuery);