2017-09-15 12:39
浏览 69


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'); ?>";


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

  //check cookies 
   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条回答 默认 最新

  • dplsnw7329
    dplsnw7329 2017-09-15 18:33

    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

    点赞 评论