CSS and JavaScript for widgets can be loaded based on widget availability. If you have created a custom widget and need to load its stylesheet only when it is active on the front end, you can use the is_active_widget WordPress function right after the parent::__construct method has been called.
class MY_Custom_Widget extends WP_Widget {
function __construct() {
$widget_ops = array(
'classname' => 'my_custom_widget',
'description' => __( 'MY Custom Widget' )
);
parent::__construct(
'my_custom_widget',
__( 'My Custom Widget' ),
$widget_ops
);
if ( is_active_widget( false, false, $this->id_base, true ) ) {
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
}
}
function enqueue_scripts() {
wp_enqueue_style( 'my-custom-widget', 'stylesheet_url' );
}
// rest of the widget code
}
Now, for loading scripts for a widget outside of the widget class, ex: loading a stylesheet for the calendar widget, you just need to figure out the widget’s unique id base.
function w4dev_load_calendar_scripts() {
if ( is_active_widget( false, false, 'calendar', true ) ) {
wp_enqueue_script( 'jquery' );
wp_enqueue_style( 'something', 'stylesheet_url' );
}
}
add_action( 'wp_enqueue_scripts', 'w4dev_load_calendar_scripts');
Note: enqueue your assets on the wp_enqueue_scripts hook, not wp_head, so WordPress can print them properly. Also, this applies to classic widgets – if your site uses the block-based widget editor (WordPress 5.8+), blocks handle their own asset loading and only enqueue assets when the block is present on the page.

Leave a Reply