Conditionally loading JavaScript based on the Advanced Custom Fields in the post

ACF has finegrained filters for fields when they get loaded.

add_action( 'wp_enqueue_scripts', 'register_my_scripts', 5 );
function register_my_scripts() {
    wp_register_script( 'my-script', 'path-to/my-script.js', array(), 'version', true );
}

add_filter('acf/load_field/name=my_field_name', 'load_field_my_field_name');
function load_field_my_field_name( $field ) {
    wp_enqueue_script( 'my-script' );
    return $field;
}

Normally all scripts should be enqueued in wp_enqueue_scripts hook. So you should make sure your script and its dependencies (which haven’t been loaded yet) can be loaded in footer. Like this your script gets enqueued when the fields are accessed in the content.

Leave a Comment