By

jQuery UI Widgets on Blog Pages

A little while ago I covered some important aspects of using the jQuery UI library inside of WordPress admin pages in the post entitled: jQuery UI in WordPress 3 Admin Pages.

This time, however, we will be focussing on how to add jQuery UI widgets into your WordPress posts/pages in a reusable way. All this will be wrapped up an a Plugin for portability. The Plugin will be uploaded to the WordPress.org Plugin repository and should be live soon, so you will be able to download it and use it on your own WordPress sites.

If you have ever tried to get jQuery, and in particular jQuery UI widgets, working on the front end of your WordPress site you may have had trouble getting everything configured correctly. You may have even had some measure of success but want to learn more. In fact, this post shows just how easy it is to get jQuery UI widgets up and running with the minimum of fuss.

Specifically we will cover how to:

  • Register and enqueue the jQuery, and jQuery UI libraries into your theme header correctly.
  • Add simple shortcode functions for each widget type.
  • Insert the shortcode and associated HTML code in a post/page to create the UI widget.

Let’s get started..

To start off with you will need to create a new Plugin file. Give the file name the same name as your Plugin name. Fill in the header information as usual. For this Plugin I have simply added:

/*
Plugin Name: jQuery UI Widgets
Plugin URI: http://www.presscoders.com/plugins/jquery-ui-widgets/
Description: WordPress Plugin to make it super easy to add-in jQuery UI widgets to your posts/pages via a shortcode.
Version: 0.1
Author: David Gwyer
Author URI: http://www.presscoders.com
*/

Next I have defined a named constant to store the path to the Plugin directory:

// Note: jquid_ prefix is derived from [jq]uery [ui] [d]emo
define("JQUID_PLUGIN_URL", WP_PLUGIN_URL.'/'.plugin_basename(dirname(__FILE__)));

This just makes it easier to reference our Plugin directory with a short, descriptive, named constant.

We need to now define an action hook to run upon page initialisation, as follows:

add_action( 'init', 'jquid_init' );

We can now flesh out the callback function to run when the hook is triggered:

// Register the blog scripts
function jquid_init(){
	if(!is_admin()){ // Only load these scripts on non-admin pages
		// Register scripts
		wp_enqueue_script( 'jquery' );
		wp_register_script( 'google.blog.jquery-ui.min', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js', array('jquery') );
 
		// Register style sheets
		wp_register_style( 'jquid_jquery_blog_stylesheet', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/sunny/jquery-ui.css' );
		wp_register_style( 'jquid_jquery_blog_custom_stylesheet', JQUID_PLUGIN_URL.'/css/custom-jquery-ui.css', array('jquid_jquery_blog_stylesheet') );
 
		// Enqueue them
		wp_enqueue_script( 'google.blog.jquery-ui.min' );
		wp_enqueue_style( 'jquid_jquery_blog_stylesheet' );
		wp_enqueue_style( 'jquid_jquery_blog_custom_stylesheet' );
	}
}

The ‘init’ action hook is triggered on admin pages too, but we only want it to add jQuery and jQuery UI on our blog pages. This is the purpose of the if(!is_admin()){ // Code to run on non-admin pages } statement. Once we can be assured our jQuery libraries will only be inserted into blog pages only we can register, and enqueue them. WordPress can then take care of adding them to the correct place in the head section of our site pages.

We want to use the jQuery library that ships with WordPress so we simply enqueue it (no need to register it as this is one of many JS libraries registered by default in WordPress). The jQuery UI library that we want to use is an external library, so this needs to be registered before it is enqueued. This is achieved by the following line of code:

wp_register_script( 'google.blog.jquery-ui.min', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js', array('jquery') );

Notice the last argument array('jquery'). This array defines the dependencies of the jQuery UI library. In short it will ensure that the JavaScript library with the ‘jQuery’ handle will be loaded before the jQuery UI is. It is not enough to add the jQuery libraries in the order you want them in the code file. You may run into trouble later on. Especially if you have many Plugins also adding jQuery libraries. To save yourself any problems, it is best to always make use of dependencies to guarantee they are loaded in the right order when the page loads in the browser.

In case you are wondering why we are using this particular jQuery UI file, it is really for simplicity and convenience. WordPress ships with several jQuery libraries including some jQuery UI but they are spread over more than one file and they don’t include everything. This one file stored on the Google API server has all the jQuery UI widgets contained inside, plus all the effects too (such as the accordion ‘bounceslide’ effect, for example)!

So, we have two jQuery libraries registered and enqueued, it is necessary to now do the same with two CSS style sheets. The first stylesheet is the main one that styles all the jQuery UI widgets, and this is registered and enqueued in a similar manner to the jQuery core, and UI libraries. The other style sheet is a custom one used to tweak the one returned from the Google API. This is necessary because (as you will no doubt find out yourself), depending on the them you have installed, you may find that your theme overrides certain elements that make your jQuery UI widgets look less than their best. An example of this is when using the Twenty Ten theme with the Plugin. The Twenty Ten CSS for the h3 tag was causing problems with rendering of the accordion widget, by adding a 20px margin to the bottom of every h3 tag. There is a slight issue with the font-size. these are both corrected in the custom style sheet. You will notice that we load the custom style sheet with the jQuery UI style sheet as a dependency to make sure it loads afterwards. Otherwise, changes to our custom one would have no effect if it was added to the page header first!

You should always use the custom style sheet to tweak to jQuery UI styles rather than from your main theme style sheet. Your main theme style sheet won’t be guaranteed to load after the jQuery UI style-sheet (in fact it probably won’t) so it is not a good idea to try and override the jQuery UI widget style from here. Just make sure to use the provided style sheet to customise the jQuery UI widget, if you need to, and you will be fine. If you are using another WordPress theme other than Twenty Ten than you might want to delete the contents of the custom CSS file and add to it as necessary (you might not even need to).

When one of your WordPress pages has loaded, view the page source and check the jQuery libraries (and style sheets) have loaded, and are in the correct order. Here is a screen shot similar to what you should see:

Right, so we have jQuery, and jQuery UI loading properly. Now it is time to use it! To insert the jQuery UI code for a specific widget on a post/page we will define a shortcode that will embed the code in the exact place we need it. It is then simply a matter of adding the associated HMTL code for the widget to render it to the page.

We will define three shortcodes, one for each type of widget we wish to display. The three we will implement are the accordion, tabs, and date picker widgets. To define shortcode for these widgets we need to add shortcode definitions to register it with the shortcode API.

add_shortcode('jQuery-UI-tabs', 'jquid_tabs_shortcode');
add_shortcode('jQuery-UI-accordion', 'jquid_accordion_shortcode');
add_shortcode('jQuery-UI-datepicker', 'jquid_datepicker_shortcode');

The first argument will be the name that will be added to a post/page. So, for instance, to add the tabs jQuery UI widget script to a page we would add [jQuery-UI-tabs] to the post/page edit screen.

Finally, it is just a case of adding in the callback function definitions that are used to output the jQuery UI script in place of our shortcode when the page loads. The three shortcode callback functions are defined as:

function jquid_tabs_shortcode(){
	echo '
	<script>
	jQuery(document).ready(function($) {
		$( "#tabs" ).tabs();
	});
	</script>
	';
}
 
function jquid_accordion_shortcode(){
	echo '
	<script>
	jQuery(document).ready(function($) {
		$( "#accordion" ).accordion({ animated: \'bounceslide\' });
	});
	</script>
	';
}
 
function jquid_datepicker_shortcode(){
	echo '
	<script>
	jQuery(document).ready(function($) {
		$( "#datepicker" ).datepicker();
	});
	</script>
	';
}

Save the Plugin and upload to your WordPress installation, and then activate it.

Now, let’s see it in action..!

Insert a shortcode in the post/page, after which you will need to add the HTML code for the UI widgets. To get you started you can simply copy the demo code from the jQueryUI.com website. For example, to get the HMTL for the accordion widget, go to:

http://jqueryui.com/demos/accordion/

and click on ‘View Source’ under then demo of the accordion. You can get the HTML source code for the other widgets by clicking on the left hand menu to load the widget you want. Don’t copy the code including the script tags, only the html contained in the div tags for the demo.

Copy the HTML into your post/page and save. View the post/page in a browser to see the jQuery UI widget displayed. The three screen shots below show the accordion, date picker, and tabs widgets in action.

In case you didn’t know it you there are many default different themes you can use with your jQuery UI widgets. You can even define your own but that is for another post! Take a look here to view all the different themes available for your jQuery UI widgets:

http://jqueryui.com/themeroller/

On the left hand side of the page click on ‘Gallery’ then scroll up/down to see all of the available theme style. Click on the preview squares (small date picker images) to see it used for all the jQuery UI widgets on the right hand side of the page. This is a nice way to quickly experiment with different theme styles.

You can very easily make your own jQuery UI widgets use a theme of your choice by editing a line in the Plugin code. Firstly pick a theme you want to try, and remember its name. For example lets change the style to the ‘Start’ theme.

In your WordPress admin panel go to Plugins -> Editor, and find the line of code in the jquid_init() function:

wp_register_style('jquid_jquery_blog_stylesheet', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/sunny/jquery-ui.css');

and change the ‘sunny’ word to ‘start’, as follows:

wp_register_style('jquid_jquery_blog_stylesheet', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/start/jquery-ui.css');

Save your changes and view the pages again in a browser. You will see that the widgets are using a different theme!

In a future release of the Plugin I will make it easier to select different themes, so you don’t have to edit code. But hey, it’s pretty easy to alter your theme with just one line of code!

To see the full Google API URL of all the jQuery UI themes you might want to check out this link:

http://encosia.com/2009/10/11/do-you-know-about-this-undocumented-google-cdn-feature/

Scroll towards the bottom of the page and you will see each theme with a Google API link in a textbox that you can copy and paste into your Plugin code.

This Plugin has been developed and tested (and works great) on a local install of WordPress running version 3.0.1, with the Twenty Ten theme active, and only a small number of Plugins enabled. If you have major problems running on a live site let me know. But deactivate some of your Plugins first as this will almost certainly be the cause of any conflicts.

Don’t forget that because we have defined the widgets as shortcodes, you can have as many shortcodes on posts/pages as you like. You can even mix and match and add multiple ones to the same post/page.

Extension will be made to this Plugin in subsequent releases are:

  • Add options page to select the gloabal theme used for all widgets.
  • Allow customisation of the jQuery UI widget shortcodes, via attributes.
  • Add more jQuery UI widget shortcodes.

If you have any suggestions the please let me know and I will do my best to add them to the Plugin.