How do I register a stylesheet inside a WordPress widget?

I’m developing a WordPress widget following Dave Clements tutorial. It works well. Now I want to add some styles to it. I want the styles to be in an extra css file which will be loaded during runtime. I’m calling this function

function myprefix_add_my_stylesheet() {
  wp_register_style( 'myprefix-style', plugins_url('mystyle.css', __FILE__) );
  wp_enqueue_style( 'myprefix-style' );
}

right before (see Dave’s tutorial) “// Widget output //” using the following statement.

Read More
add_action( 'wp_enqueue_scripts', 'myprefix_add_my_stylesheet' );

But nothing seems to happen. What am I doing wrong?

Related posts

Leave a Reply

1 comment

  1. wp_enqueue_scripts is called way before WordPress processes the widget content, so just as in this post, you’ve missed the boat :).

    Instead, just call wp_enqueue_style directly:

    function widget($args, $instance) {
        wp_enqueue_style( 'myprefix-style', plugins_url('mystyle.css', __FILE__) );
    
        //Widget content
    }
    

    (no need to register if you’re just going to enqueue it straight after). Same works for wp_enqueue_script.