0

The code below is part of a widget that goes with my theme. I'm trying to include a stylesheet that the widget needs by placing an add_action call to wp_head. However, the function never fires in this context.

What am I missing?

   function widget( $args, $instance ) {
        if(!get_option('my_slider')) return;
        add_action('wp_head', 'my_sliderCSS');
        extract($args);
        $title = apply_filters( 'widget_title', empty($instance['title']) ? '' : $instance['title'], $instance );
        $text = apply_filters( 'widget_text', $instance['text'], $instance );
        $hide_title = isset( $instance['hide_title'] ) ? $instance['hide_title'] : false;
        echo $before_widget;
        if ( $title && !$hide_title )echo $before_title . $title . $after_title;
        if ( $text )?><div id="slider"><dl><?php echo $instance['filter'] ? wpautop($text) : $text; ?></dl></div>
        <?php echo $after_widget;
    }
2
  • 1
    Do you mean that my_sliderCSS does not fire? I'm afraid that wp_head has long fired off before your widget() (choice of name may collide with something else, careful) is called, place your add_action code inside your widget initialization.
    – soulseekah
    Oct 21, 2011 at 12:37
  • Also check if(!is_admin()) before enqueue()-ing as there's no point in adding the CSS to the admin area. Or... just switch 'wp_head' with 'wp_footer' and at the CSS at the end :) Oct 21, 2011 at 22:01

1 Answer 1

2

There are various approaches (including this one), but you could consider, since you're talking about a stylesheet and not a script, simply enqueueing it from the Plugin, regardless of whether the Widget is active. (Which is worse: the few bytes of Widget-specific CSS, or the server overhead to determine if the Widget is active?)

Just add the following to your Plugin file (outside of the Widget class definition):

<?php
function plugin-name_print_stylesheet() {
    ?>
    <style type="text/css">
    /* CSS definitions go here */
    </style>
    <?php
}
add_action( 'wp_print_styles', 'plugin-name_print_stylesheet' );
?>

Or, if you've got a .css file with your Widget's stylesheet:

<?php
function plugin-name_enqueue_stylesheet() {
    wp_enqueue_style( 'plugin-name-stylesheet', plugins_dir( 'stylesheet.css', __FILE__ ) );
}
add_action( 'wp_enqueue_scripts', 'plugin-name_enqueue_stylesheet' );
?>

p.s. don't use a generic term such as my_slider as a custom-function prefix. You should use your plugin-slug instead, as a prefix for all of your Plugin's custom functions.

Your Answer

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

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