duanjian9148 2017-09-15 12:39
浏览 94
已采纳

将高级自定义字段添加到javascript

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

  • 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题