Notes

Adding a stylesheet to a WordPress plugin

Edit on GitHub

PHP
2 minutes
1function add_my_stylesheet()
2{
3    wp_enqueue_style( 'myCSS', plugins_url( '/css/myCSS.css', __FILE__ ) );
4    wp_enqueue_style( 'myCSS1', plugins_url( '/css/myCSS1.css', __FILE__ ) );
5    wp_enqueue_style( 'PopularUsers', plugins_url( 'PopularUsers.css', __FILE__ ) );
6}
7
8add_action('admin_print_styles', 'add_my_stylesheet'); // Plugin Admin
9add_action( 'wp_enqueue_scripts', 'add_my_stylesheet' ); // Site CSS

Another example where i was adding a shortcode and wanted to add the styles for web pages from within the plugin

1// Load the CSS file
2function plugin_popularUsers_stylesheet()
3{
4  wp_enqueue_style( 'PopularUsers', plugins_url(
5    'PopularUsers.css', __FILE__ ) );
6}
7add_action('wp_enqueue_scripts', 'plugin_popularUsers_stylesheet');

You will use the following functions

  • wp_enqueue_style
  • plugins_url
  • admin_print_styles (for adding stylesheet to PLugin’s admin)
1// wp_enqueue_style( $handle, $src, $deps, $ver, $media );
2
3wp_enqueue_style('slider', get_template_directory_uri() . '/css/slider.css', false,'0.2','all');

if it is enqueued, then it will be printed out in an HTML <link ...> element in the <head></head> section in the same manner that WordPress loads it’s own stylesheets.

  • You just have to pass the filename for the CSS file (without the .css extension). For example slider instead of slider.css.
  • You can get the current plugin’s dirtectory with plugins_url(). For example:
1// plugins_url( string $path = '', string $plugin = '' )
2
3plugins_url( '/css/myCSS.css', __FILE__ )

this will get the myCSS.css file from inside the css folder in the current plugin’s directory (relative path)

If you want to add stylesheet for Plugin’s admin/settings area, you’d use admin_enqueue_scripts

1add_action( 'admin_enqueue_scripts', 'plugin_stylesheet_to_admin' );

Both admin_enqueue_scripts and admin_print_styles should work