Support » Plugins » multiple instance widget and wp_print_styles

  • I have created a widget using the 2.8+ Widget API that extends the WP_Widget class. For each Widget instance, the user can select from multiple pre-defined .css styles. However, I have found no way to pass the selected style to the wp_print_styles hook using the wp_register_style, wp_enqueue_style method within the class.

    Any ideas on how to allow each instance of a widget to load an assigned css style conditionally (once).

Viewing 2 replies - 1 through 2 (of 2 total)
  • While multiple instances of the widget are being created with user-defined settings, these are the ways that do NOT seem to work when trying to insert a .css file based on the instance style setting.

    1. Register, enqueue then print a link to a style file in the header for THAT widget instance while it is being created.

    2. Create an array, make it global in the class, save the css file name to the array like:
    $style_arr[$style_name] = $style_name;
    then, after looping through all instances of the widget, loop through the style array and insert the required styles into the head. While the global array will save the style names, there does not seem to be a way to call the wp_print_styles function after the style array has been populated.

    Currently, I am just printing out all possible styles in the head, regardless if they are needed or not. Clumsy, not efficient and not at all flexible. Anyone? Bueller? Bueller?

    hey Baden, I found a stop-gap, band-aid, until-the-correct-solution comes around fix for you:

    1. create a WordPress option for all styles:
      add_option('your_widget_styles', '');
    2. as each widget instance is updated, assign the styles used to the WordPress option:
      $style_arr = get_option('your_widget_styles');
      $style_arr[$instance['style']] = $instance['style'];
      update_option('your_widget_styles', $style_arr);
    3. add the wp_print styles function like so:
      function countdown_style(){
              $styleizer = get_option('your_widget_styles');
      	$plugin_url = trailingslashit( get_bloginfo('wpurl') ).PLUGINDIR.'/'. dirname( plugin_basename(__FILE__) );
      		foreach((array) $styleizer as $style){
      			wp_register_style( 'widgetname-'.$style.'-css', $plugin_url.'/css/'.$style.'/style.css', array (), '1.0' );
      			wp_enqueue_style( 'widgetname-'.$style.'-css' );
      add_action( 'wp_print_styles', 'widgetname_style');

    There are two limitation that this method has:
    1. After adding or changing to a new style, the page must be reloaded once to store the style array… and then after that it will display properly.
    2. Once a style is used, it will always the style.css file will always be inserted.
    Hope this helps!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘multiple instance widget and wp_print_styles’ is closed to new replies.