0

I'm using the Bones theme, and I'm trying to turn jQuery plugins into WordPress plugins. In the init.php file for the 'Chosen' plugin I'm converting, I've included this code:

function chosen(){
    wp_register_script("chosen-script",plugins_url( 'js/chosen.jquery.min.js' , __FILE__ ));
    wp_enqueue_script("chosen-script");
    wp_register_style("chosen-style",plugins_url( 'css/chosen.css' , __FILE__ ));
    wp_enqueue_style("chosen-style");
}

add_shortcode('chosen', 'chosen');

Google PageSpeed came back with this error:

Put CSS in the document head (1):

Link node chosen.css should be moved to the document head in www.blank.com/

How can I include this CSS file in the header?

4
  • 2
    You should hook the function that registers and enqueues the scripts onto wp_enqueue_script. add_action( 'wp_enqueue_scripts', 'chosen' ); rather than as a shortcode. Commented Mar 7, 2014 at 23:43
  • Thank you Andrew, that did it. The only problem is that now the plugin in loaded on every page of my site. With 'add_shortcode', the plugin was loaded only on pages that contained the 'chosen' shortcode. Is there a way without 'if' statements to include the plugin only on specific pages?
    – eclipsis
    Commented Mar 7, 2014 at 23:51
  • In regards to my last question, this is how I would load it on a specific page: if (is_page('to-do_list'))
    – eclipsis
    Commented Mar 8, 2014 at 0:06
  • To dynamically load stylesheets in the head based on a shortcode, you will have to do something like this which is admittedly a bit processing heavy.
    – s_ha_dum
    Commented Mar 8, 2014 at 0:22

1 Answer 1

1

By the time the shortcode is evaluated as part of the_content the header of the site has already been assembled. This makes it impossible to load scripts or styles in the header anymore.

As s_ha_dum suggests you could pre-process the whole post in the head of the file, but that would probably consume more resources than indiscriminately adding the js+css files to the header.

Another, also quite elaborate, approach would be to hook into save_post and set a postmeta flag indicating whether the shortcode is used in the post. You could then read the flag while still in the head and include the js+css files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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