Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm having problems with jQuery and a plugin, the console error says jQuery is not defined. What I don't understand is it only fails when I load it to the production server, on my local dev installation it worked perfectly.

ReferenceError: jQuery is not defined.

The plugin code:

add_filter( 'wp_footer', 'enqueue_footer_scripts', 9);
add_filter( 'wp', 'enqueue_styles', 11);

function enqueue_footer_scripts() {
    wp_register_script( 'sjs', plugins_url('/js/sjs.js', __FILE__), array('jquery'));
    wp_enqueue_script( 'sjs' );
    echo "<script>jQuery(document).ready(function ($) { $('p').sJS();});</script>"; 
}

function enqueue_styles() {
    wp_register_style('sjcss', plugins_url('/css/sjs.css', __FILE__), false, '2.1');
    wp_enqueue_style('sjcss');
}
share|improve this question
    
You are doing it wrong. use wp_enqueue_scripts. Check the code for functions.php you posted. Its the proper way to enqueue script. –  Sisir Mar 11 at 9:20
    
Please don't shout that much. Also don't use tags in the body of your question. –  Pieter Goosen May 22 at 7:15

2 Answers 2

up vote 2 down vote accepted

Your code doesn't work because of a fundamental ordering problem.

You're hooking into wp_footer. Then you're registering a script and enqueueing it. Finally, you echo some code.

Here's the problem, the act of enqueueing a script does not cause an echo of the script code immediately. Enqueueing does just what it says, it sets the script up to be added to the page output at a later time. So your echo of the script code here is too early.

Specifically, the enqueued scripts for the footer happen in the wp_print_footer_scripts call, which is connected to the wp_footer action with priority 20. So you need to enqueue before then, but print your custom script code after then.

So make a new function. Hook it to the wp_print_footer_scripts action. Then move your echo code into that, but leave the enqueue code where it is.

share|improve this answer

Straight from the Codex this is how to load a script:

function my_scripts_method() {
    wp_enqueue_script( 'social-highlighter-js', plugins_url('/js/social-highlighter.js', __FILE__), array('jquery'));
}

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

Then print your custom initialization scripts in the footer:

add_filter( 'wp_print_footer_scripts', 'my_wp_print_footer_scripts' );

function my_wp_print_footer_scripts() {
    echo "<script>jQuery(document).ready(function ($) { $('p').socialHighlighterShare();});</script>";  
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.