0

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?

danyo
  • 5,686
  • 20
  • 59
  • 119
  • Have you added an ob_start()? – Anigel Jun 27 '13 at 16:10
  • Are you after guessed answers by leaving out your actual PHP code and the complete error message? Where did you read `ob_flush()` would help? – mario Jun 27 '13 at 16:11
  • possible duplicate of [Headers already sent](http://stackoverflow.com/questions/8028957/headers-already-sent-by-php) – mario Jun 27 '13 at 16:13
  • @Anigel - sorry i meant ob_start(); – danyo Jun 27 '13 at 16:14
  • @mario - i added this at the very top of the functions.php – danyo Jun 27 '13 at 16:14
  • @mario how is this a duplicate? it's a different scenario.... – danyo Jun 27 '13 at 16:16
  • `functions.php` is for Wordpress code, not folding in Javascript snippets. Consider the templates, where your HTML output resides. Also consider actually reading the link. – mario Jun 27 '13 at 16:19
  • so if im creating a function in the functions.php your telling me to add js in my theme template? – danyo Jun 27 '13 at 16:32

1 Answers1

0

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.

Community
  • 1
  • 1
brasofilo
  • 25,496
  • 15
  • 91
  • 179