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:
-
<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:
-
define('THIS_PLUGIN_URL', WP_PLUGIN_URL.'/YourPluginName'); // handles correct plugin location post WP2.6
-
-
function display_headAdmin()
-
{
-
echo '<link rel="stylesheet" type="text/css" href="'.THIS_PLUGIN_URL."/admin.css" .'" />';
-
}
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.
-
// add the admin page stylesheet
-
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.