Using jQuery UI CSS in admin screen

I work on new plugin and I need jQuery UI in admin screen. Well, it’s a common situation. Besides the javascript, I also need jQuery UI stylesheet. How to include proper CSS into your WordPress? It’s not that hard.

First, we need to include jQuery and jQuery UI. As an example, we will also use jQuery UI Tabs. Normally we may use Google APIs, but while we are in WordPress environment, we should use jQuery provided. So, let’s write some class:

So, what we’ve got here? This code will include jQuery, jQuery UI, jQuery UI Tabs (because those are our dependencies) and plugin.js – our main javascript file located in /assets/js folder.

Of course, it isn’t very good example. While developing plugin, we are using some admin sub pages, so let’s add one:

This code adds “Plugin” sub menu in “Posts” menu.

Is that good enough? Unfortunately not. Why? Because this code adds our javascript on every and each admin screen. It’s unnecessary wasting of our users time. We should include this code only on our admin screen. So, let’s add some code:

Does it work? Yes, it is. This is exactly what we need. So… where is the CSS? Well pointed. We’ve got javascript on our screen, so let’s add CSS. We will need out jQuery version (because CSS styles may differ from version to version) and theme name. We will add this code in admin_enqueue_scripts method:

This code make sure that we use proper jQuery version and, of course, you may change your default theme. Refer to jQuery UI documentation for more theme names. You also have to add simple html to use tabs. Final PHP code should look like this:

And your plugin.js file should look like this:

Be the first to comment

Leave a Reply

Your email address will not be published.