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 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?