Add stylesheets and js to template files when shortcode is used

After looking for days throught the net and no avail – i’d like to ask all of you guys.

PROBLEM: i need to add custom code to the head of the file as part of shortcode use for my plugin. The same files and code insert fine in the admin page (backend) but fail to load in the template file.

Read More

The files are inserted in the admin head with add_action(‘admin_print_scripts’, ‘add_swm_scripts’); & add_action(‘admin_print_styles’, ‘add_swm_styles’); calls pointing to functions that use wp_enqueue_script() and wp_register_style() / wp_enqueue_style()
This does fine – however – when i try to get the same files registered in the function of the shortcode (for use in the template), nothing workds.

I checked that the shortcode is read and it’s according function is fired, but neither add_action( ‘wp_enqueue_scripts’, ‘swm_scripts’ ); , add_action(‘init’, ‘register_swm_scripts’); nor add_action(‘wp_head’, ‘print_swm_scripts’); will work.
I’ve tried more than this not don’t find a working solution. If somebody knows a valid trick – i more than appreciate some advice.

Thanks in advance!

Herbie

Related posts

Leave a Reply

1 comment

  1. put wp_enqueue_script() in your shortcode handler.

    add_shortcode('myshortcode', 'my_shortcode_handler');
    
    function my_shortcode_handler($atts) {
      wp_enqueue_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);
    
      // actual shortcode handling here
      return "bacon flavored shortcode here";
    }
    

    this definitely loads the my-script.js file for me. it gets loaded in the footer though. i don’t think there is a way for it to load conditionally in the header as it won’t have gotten to the post content to know whether the shortcode is used or not.

    check this:
    http://scribu.net/wordpress/conditional-script-loading-revisited.html