WordPress: style your plugin admin page

November 4th, 2009


About the Author

Dan Smart photo
I’m Dan Smart, a 32 year old website developer, based in Swansea, UK. I have worked in the software development industry for over 10 years, with experience in web development, mobile handset development, and mobile networks. My current focus is web development, working freelance with a number of clients, working both on design and implementation of websites and web applications with systems such as Wordpress, Joomla, and CodeIgniter. When I’m not developing websites and software, I am a keen runner, involved with mime performance group Innovo Physical Theatre, and also actively involved in my local church.

* Follow me on Twitter or contact me


I was recently designing a WordPress plugin, and was looking for a way to style its fairly complicated admin page.

To style the output of the plugin content in the site itself is fine, I would just use wp_enqueue_style(...). However, as far as I’m aware, this isn’t available for admin plugin screens.


Far from ideal: Styling elements

Most people style their plugin admin screens with style elements, for example:

  1. <div style="color: white; background-color: red">…</div>

However this gets rid of the benefit of stylesheet classes, and easy updateability of the styles. There must be a better way than this I thought.

Solution: Including the admin page stylesheet

The solution is in fact fairly simple, but not many people seem to have used it or written about it.

In the same way that you can add to the head of a wordpress page using the wp_head action, so you can add to the head of an admin page using the admin_head action

So, create a stylesheet (in this situation called admin.css) that contains the files, in your plugin folder.

Then in your plugin code, define a function to link to the stylesheet:

  1. define('THIS_PLUGIN_URL', WP_PLUGIN_URL.'/YourPluginName'); // handles correct plugin location post WP2.6
  2.  
  3. function display_headAdmin()
  4. {
  5.   echo '<link rel="stylesheet" type="text/css" href="'.THIS_PLUGIN_URL."/admin.css" .'" />';
  6. }

This function outputs the link to the admin.css stylesheet.

Then all we have to do is add this hook into WordPress, using the admin_head action.

  1.   // add the admin page stylesheet
  2.   add_action('admin_head', 'display_headAdmin');

Note
This could also be used to link a script into your admin panel also, by adding a link in from the display_headAdmin function.

Conclusion
I hope this is useful. Have I missed an obvious way? Let me know in the comments below.

Leave a Reply


Switch to mobile version