1

I have created an ACF option in the admin so a user can add cookie notice text via the admin...The javascript script I'm using creates the message within the javascript so I'm wanting to echo the ACF field within the javascript.

At the top of my cookie.js file I have: "<?php $cooke_msg = the_field('cookie_notice', 'option'); ?>"; and I'm echoing it within a var like so: var msg = "<?php echo $cookie_msg; ?>"; so the top of my file looks like this:

"<?php $cooke_msg = the_field('cookie_notice', 'option'); ?>";

(function(){

  //Change these values
  var msg = "<?php echo $cookie_msg; ?>";
  var closeBtnMsg = "OK";
  var privacyBtnMsg = "Privacy Policy";
  var privacyLink = "https://www.google.com";

  //check cookies 
  if(document.cookie){
   var cookieString = document.cookie;
   var cookieList = cookieString.split(";");
   // if cookie named OKCookie is found, return
   for(x = 0; x < cookieList.length; x++){
     if (cookieList[x].indexOf("OKCookie") != -1){return}; 
   }
  }

What I'm getting when I view the site is: <?php echo $cookie_msg; ?> and not the actual message from ACF...is there a way of actually doing this?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.