TransWikia.com

how to enqueue javascript to manipulate acf input field in admin?

WordPress Development Asked by Stefan Avramovic on December 23, 2020

I have an acf field ‘select’ that i want to remove some options from using js

but i can not acces the field it returns undefined

<select id="acf-block_5f35006ff2da4-field_5f3cce8a89941" 
class="" 
name="acf-block_5f35006ff2da4[field_5f3cce8a89941]" 
data-ui="0" data-ajax="0" 
data-multiple="0" 
data-placeholder="Select" 
data-allow_null="0">
<option value="transparent">Transparent/bakgrundsfärg</option>
</select>

I have tried with

    document.addEventListener("DOMContentLoaded", function(event) {
     
     console.log("loaded") //Prints out: loaded


      var element = document.getElementById("acf-block_5f35006ff2da4-field_5f3cce8a89941");
      console.log(element)// Prints out: undefined


}),

It seams that the block is not finished loading when DOMContentLoaded is triggerd

add_action('admin_enqueue_scripts', function ($hook) {



    $file = sprintf("%s/js/wp-admin_blocks.js", get_template_directory());

    if(file_exists($file)) {

        $mtime = filemtime($file);
        wp_enqueue_script('ams-blocks', sprintf("%s/js/wp-admin_blocks.js", get_template_directory_uri()), [], $mtime, true);
    
    }


});

One Answer

Maybe an easier approach would be to remove the values before the input is presented in the admin? That would circumvent having to do things in JavaScript after the field is already displayed.

Take a look at acf/prepare_field hook:

function my_acf_prepare_field( $field ) {
    unset($field['choices']['custom']);

    return $field;
}

// Apply to all fields.
// add_filter('acf/prepare_field', 'my_acf_prepare_field');

// Apply to select fields.
// add_filter('acf/prepare_field/type=select', 'my_acf_prepare_field');

// Apply to fields named "custom_select".
add_filter('acf/prepare_field/name=custom_select', 'my_acf_prepare_field');

// Apply to field with key "field_123abcf".
// add_filter('acf/prepare_field/key=field_123abcf', 'my_acf_prepare_field');

If you are set on JavaScript, you can use ACF's JavaScript hooks:

acf.add_action('ready', function( $el ){
    
    // $el will be equivalent to $('body')
    
    
    // find a specific field
    var $field = $('#my-wrapper-id');
    
    
    // do something to $field
    
});

Documentation here: https://www.advancedcustomfields.com/resources/adding-custom-javascript-fields/

Answered by NightHawk on December 23, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP