如何在管理员中将javascrip排入队列来操作ACF输入域?

时间:2020-08-20 作者:Stefan Avramovic

我有一个acf字段“select”,我想从使用js中删除一些选项

但我无法访问它返回的未定义字段

<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>
我试过了

    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


}),
触发DOMContentLoaded时,它表明块尚未完成加载

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


});

1 个回复
SO网友:NightHawk

也许更简单的方法是在输入显示在管理中之前删除这些值?这将避免在字段已经显示后必须在JavaScript中执行操作。

看看acf/prepare_field 挂钩:

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\');
如果设置为JavaScript,则可以使用ACF的JavaScript挂钩:

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
    
});
此处的文档:https://www.advancedcustomfields.com/resources/adding-custom-javascript-fields/

相关推荐