The class constructor method isn’t called until your shortcode handler is (i.e. when WordPress is searching the post content for shortcodes). This is done after wp_head
is called, so you’re missing the boat.
However, you don’t need to enqueue scripts on your wp_head
– and doing so for shortcodes/widgets which may not be on every page is a waste. Since 3.3 you can call wp_enqueue_script
inside the shortcode/widget callback, and doing so means your script is enqueued only on pages where it is absolutely needed. The script is then printed in the footer.
class AV_Slideshow{
function build_slideshow($slides){
if(!$slides){$slideshow = 'No posts are selected for this slideshow.';}
$slideshow = '<div id="slides"><div class="slides_container">';
foreach($slides as $post_id){
$post = get_post($post_id);
$title = $post->post_title;
$content = $post->post_content;
$slideshow .= '<span>' . $title . '</span><span>' . $content . '</span>';
}
$slideshow .= '</div></div>';
//Shortcode is being used, so enqueue the script:
wp_enqueue_script('av-slideshow', get_bloginfo('stylesheet_directory') . '/js/AV-Slideshow/av_slideshow.js', array('jquery') );
return $slideshow;
}
}
add_shortcode( 'slideshow', array('AV_Slideshow', 'build_slideshow') );
After that slimming down, the class structure seems a bit unnecessary. But I tend to put all my plug-in’s shortcodes into one class – particularly when the shortcodes are sharing scripts/styles and I need to print JavaScript variables to the page.