0

I want to create checkboxes with Advanced Custom Fields in an admin panel in the Wordpress backend that can enable and disable scripts.

I created a checkbox field, called it import_animejs and checked it. Then used acf/load_field to enqueue the script but I am missing something as it's not working.

Here is my code:

function acf_checkbox_scripts() {
    wp_register_script('animejs', get_stylesheet_directory_uri() . '/bower_components/animejs/lib/anime.min.js', array('jquery'),'1.1', true);
}
add_action( 'wp_enqueue_scripts', 'acf_checkbox_scripts', 5 );

function load_field_import_animejs( $field ) {
    wp_enqueue_script('animejs');
    return $field;
}
add_filter('acf/load_field/name=import_animejs', 'load_field_import_animejs');

I expect the filter to recognise that import_animejs is ticked and enqueue anime.js but it doesn't.

Update: many thanks to Lachlan's answer this works, and just for clarification I completely removed the acf/load_field "load_field_import_animejs" function in the code I posted above.

Alex
  • 3
  • 4

1 Answers1

0

You need to do an if statement and check if the field is true

This can be done by:

function acf_checkbox_scripts() {
    if ( get_field( 'import_animejs', 'options' ) ) { // only include 'options' if the acf field is on an acf options page, if not use the post_id of that page
        wp_register_script('animejs', get_stylesheet_directory_uri() . '/bower_components/animejs/lib/anime.min.js', array('jquery'),'1.1', true); 
        wp_enqueue_script('animejs');
    }
}

add_action( 'wp_enqueue_scripts', 'acf_checkbox_scripts', 5 );