doudao8283 2013-06-27 16:06
浏览 117

如何将自定义javascript添加到wordpress functions.php

I currently need to add some custom jQuery to my wordpress functions, i have added jQuery the following way:

add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
   wp_deregister_script('jquery');
   wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
   wp_enqueue_script('jquery');
}

I need to add the following:

$(document).ready(function () {
$(".infobfn").append('<a href="#" rel="tooltip" title="<?php echo $variable; ?>"><i class="icon-info-sign"></i></a>');});

The problem i have is that i cant add this to an external .js file as it contains php variables.

With it left in my functions i get the following:

Warning: Cannot modify header information - headers already sent by

I have added ob_start(); which was recommended. I though this worked, but then realised only half of my page had loaded.

i am currently not using php header within my functions.php and have also checked for white space.

Any ideas how i can get around this?

  • 写回答

1条回答

  • douzhou7656 2013-07-06 19:00
    关注

    Two things you're doing wrong:

    1. Dequeuing WP bundled jQuery

    2. Using jQuery without noConflict mode. The following example is the proper way to do it:

    jQuery(document).ready(function($) {   
        // Now, $ will refer to jQuery
        // Write all your logic inside this block
    });
    

    And, to solve the use of PHP variables inside your Javascript file, use wp_localize_script. This function will pass any variables you want to a properly enqueued Javascript file.

    Check this Answer for a working example.

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题