Use wp_enqueue_style based on user option in widget

I currently developing wordpress widget for my website. This widget will pull user latest post in my website and show in their blog.

In the widget there is option for user to use their css or my css for the widget

I use this code in my widget and its work perfectly but this code will always load the css.

add_action( 'widgets_init', 'load_my_widgets' );

function load_my_widgets() {
    register_widget( 'My_Widget' );
    wp_register_style( 'my_widget_css', 'http://mydomain.com/css/my-widget.css' );
    wp_enqueue_style( 'my_widget_css' );
}

The problem is how can I enable the CSS based on the user option? I try something like this but its not working

function widget( $args, $instance ) {
    $own_css = isset( $instance['own_css'] ) ? true : false;

    if ( ! $own_css ) {
        wp_enqueue_style( 'my_widget_css' );
    }
}

3 Answers
3

This is sort of sloppy as the style will still be enqueued regardless.

In the code to display your widget, change the CSS selectors based on whether or not the user selected own style:

<?php
$prefix = $instance['own_style'] ? 'ownstyle_' : 'pluginstyle_';

//then....
?>
<div id="<?php echo $prefix; ?>selector"> ...</div> etc

A user would be able to use both a widget with custom style and one with default style this way. Enqueue your style separately in its own function.

add_action( 'wp_print_scripts', 'wpse26241_enqueue' );
function wpse26241_enqueue()
{
    if( is_admin() ) return;
    if( is_active_widget( 'My_Widget' ) )
         wp_enqueue_style( 'my_style' );
}

Leave a Comment