Classic Allison: late to the party! But better late than never. Let’s talk about using ACF fields within a JS file.
<?php wp_localize_script( $handle, $name, $data ); ?>
This allows you to translate string values, if necessary.
Keep in mind that you need to be using
wp_register_script() prior to this function being called for it to work.
wp_enqueue_script() function. This is the file that will use the variables we’re grabbing.
For instance, in this case I’m enqueuing a file called ‘atarr-super-heroine’:
<? wp_enqueue_script( 'super-heroine', get_template_directory_uri() . '/assets/js/super-heroine.js', array(), $version, true ); ?>
So, when we want to localize the script, we’ll use that name (super-heroine) for the first parameter as seen below.
<? wp_localize_script( 'super-heroine', 'acf_vars', array( 'list_parent' => get_field( 'heroine_secret_identity' ), ) ); ?>
The second parameter (acf_vars) can be named whatever you’d like to refer to your object as. In my case,
acf_vars. The array I passed as the third parameter grabs the ACF field that is named
'heroine_secret_identity' with a key that I named
Accessing the Variables
To access these variables, we go within the
super-heroine.js file that we’ve listed as the first parameter. We use what we passed as the second parameter to access the variables followed by the designated key. In my case, the variables were two repeaters within a grouping (
const desc = acf_vars.list_parent.descriptor_list; const subj = acf_vars.list_parent.subject_list;
From there, take the variables and use them however you need to within your JS file. Voilà!
- WordPress Codex: wp_localize_scripts