如何将自定义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?

dongpeihui1051
dongpeihui1051 所以如果我在functions.php中创建一个函数你告诉我在我的主题模板中添加js?
大约 7 年之前 回复
dongzou7134
dongzou7134 functions.php用于Wordpress代码,不能在Javascript片段中折叠。考虑HTML输出所在的模板。还要考虑实际阅读链接。
大约 7 年之前 回复
drnmslpz42661
drnmslpz42661 怎么这是重复的?这是一个不同的场景......
大约 7 年之前 回复
dongmeng1875
dongmeng1875 -我在functions.php的最顶部添加了这个
大约 7 年之前 回复
dsxgby126001
dsxgby126001 -对不起,我的意思是ob_start();
大约 7 年之前 回复
dseslyh6662605
dseslyh6662605 已发送的标题可能重复
大约 7 年之前 回复
dpnvrt3119
dpnvrt3119 您是否通过省略实际的PHP代码和完整的错误消息来猜测答案?你在哪里读到ob_flush()会有帮助吗?
大约 7 年之前 回复
doukuipai8544
doukuipai8544 你添加了ob_start()吗?
大约 7 年之前 回复

1个回答



你做错了两件事:</ p>


  1. Dequeuing WP捆绑jQuery </ p>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问