Get ACF value in external jQuery document

I’m trying to get the value of an Advanced Custom Fields select list in an external jQuery document, in order to apply some conditions to it.

I looked for an answer and found only solution involving the use of tags inside the page, which I want to avoid.

1 Answer
1

Your question is not entirely clear, but it looks like you are in need of wp_localize_script, which allows you to pass variables from PHP to a script. You would use it like this (example with two fields):

add_action ('wp_enqueue_scripts','wpse244551_add_field');
function wpse244551_add_field () {
  $my_field = array ();
  $my_field[] = array (field1 => get_field ('field1'));
  $my_field[] = array (field2 => get_field ('field2'));
  wp_localize_script ('my-script', 'MyFields', $my_field);
  }

Now, in the script you have registered with the handle my-script you can access the variable with MyFields.field1 and MyFields.field2.

Leave a Comment