Wordpress / ACF | pass PHP variable data to js file *

https://www.advancedcustomfields.com/resources/javascript-api/
https://www.advancedcustomfields.com/resources/adding-custom-javascript-fields/
https://support.advancedcustomfields.com/forums/topic/when-to-use-the-acf-javascript-api/


https://stackoverflow.com/questions/46239827/adding-advanced-custom-field-to-javascript

 

Wordpress giving nice function to pass PHP variable data to js file.

Put this code in your theme functions.php page.

function mytheme_load_scripts() {

    wp_enqueue_script('mytheme-script', get_template_directory_uri() . '/js/mytheme-script.js');
    wp_localize_script('mytheme-script', 'mytheme_script_vars', array(
        'alert' => get_field("cookie_notice",$post_id)
        )
    );

 }
 add_action('wp_enqueue_scripts', 'mytheme_load_scripts');

And Create one js folder in your theme root directory. Inside that directory create the js file named mytheme-script.js file, & put the below code over there.

jQuery(document).ready(function($) {

 alert( mytheme_script_vars.alert );

});

Now visit any page of your site. Surely you will get an alert with the your desire field value. Make sure you will assign proper value to $post_id. I think this will help you. Codex reference link for more details: WP Localize Script Function

 

  • It's recommended to escape the output of any user-input like this: 'alert' => esc_attr( get_field("cookie_notice",$post_id) ). esc_attr is one of many functions built into WordPress which prevents malicious scripts from being accidentally output on the frontend.

    admcfajn

    Apr 12 '19 at 0:18

Scroll to Top