Build a jQuery Tabbed Widget for Wordpress
You have seen them. You have loved them. And now my friends, you will have one. A tabular widget area is a handy little way to display a couple widgets in one, such as recent comments, posts or category list. And the added effects of sliding around make it pretty to look at, so why not make one of your own?! This tutorial will walk you through the steps to create your own widget for use in any of your WordPress themes, and we will enhance it with some jQuery love to make transitions a little fun. Enough talk, let’s build!
We will be working mostly with PHP here, but don’t let that scare you off if you never have played with it before, we will take this journey together. As always, we will work in steps. For the impatient, (yes you!) you can jump around here.
Going Somewhere?
A lot of people I have seen asking about how to make a custom landing page for their WordPress website. Instead of having the standard post listing be displayed, to give it more of a “website” type feel to it. So in this post we will walk through creating a totally customized, and widgetized, home page for your WordPress site.
Here is what it will do, sans any styling
Widget PHP
Top
Wordpress is generous as they give us a beautiful class to build off when extending our widget. The basic skeleton remains the same for any variety of widgets you wish to create, so create a new file and name it tabbed_box.php or something similar. Paste this following dummy structure into it,
"A Tabbed Box Widget", "class" => ""));
}
function widget($args, $instance) {
extract( $args );
global $wpdb;
$title = apply_filters('widget_title', $instance['title']);
?>
}
function update($new_instance, $old_instance) {
return $new_instance;
}
function form($instance) {
}
}
add_action('widgets_init', create_function('', 'return register_widget("tabbed_box");'));
?>
Keep in mind this is a skeleton, and we will be working inside some of these functions. So, mind the brackets!
What? Exactly, it looks a little strange, but mostly just because it is empty. So this starts out by creating a new class cleverly named tabbed_box that extends the WordPress default widget class. Meaning that it can use what is already there, and build upon it. Saves a lot of work. The first line inside the class instantiates our tabbed_box function, and informs WordPress, “Hey, I am your son! Give me your codes!” Being the kind parent that WordPress is, he let’s our newborn get to work.
Our second function in this class, aptly named widget is the workhorse of what we are building. This is where the fun will happen, all that is in there now is code to grab the information passed into it, and a way to add a title to our widget from its options dialog. we will get to that later.
The next function, update, is already done! Yay! And you thought this would be hard? All this does is literally update options for what our widget should do, it takes in the new and removes the old. Done.
You can gues what the last one does, this function controls the form that appears in the widget itself when you drag it to your sidebar. This is where we will get the options to send into the widget function.
Last but definitely not least, we have to tell WordPress what we just did. The add_action function basically takes everything we are building here, and hooks it into WordPress thus displaying the widget and making it available for use. Still with me? Sweet, now we get to make it do something.
So I have decided that this widget will have three tabs; one for recent comments, one for recent posts and one to show my tags. So we will start by grabbing some data from WordPress, we will get the most recent posts, comments and form a tag cloud. Paste this into the widget function, directly below the line
get_results($wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_approved = 1 ORDER BY comment_date DESC LIMIT ".$comment_count, "ARRAY_A") );
$tag_count = count(wp_tag_cloud('format=array'));
?>
Don’t even lie, you know that looks fun!
The variable $instance is referring to the instance of our widget, so the line is saying, “check this current widgets form fields to see if anything was input into the field names $post_count, and if not make it 3″. I hope that makes sense. Ok, so that is what we check here, to see if the user input a number in our widget options for how many posts to show, and if not we set a default view of 3.
Following this we set up a variable named named $tab_posts, and this is just to hold our custom query string. The string will tell the loop how many posts to display, based on user input. You can see that the string “showposts” is concatenated with the variable we made to hold how many posts to show. We then do the exact same thing for the number of comments to show, the only difference is the PHP function esc_attr() which we use to encode the input field string because we will send it into a database. So then yet another variable is created, $recent_comments, and this we set equal to an SQL query that looks scary, but all it does is take our input value and ask the database for that number of recent comments.
And finally a variable that holds our tag cloud, this function is straight from WordPress Codex here.
Now to build what our widget will look like, remember we are still working inside of the widget function, so be sure this code goes right under where we left off.
<li class="tabbed_box"> <ul class="box_tabs"> <li class="tab selected"><a id="tab_link_1">Comments</a></li> <li class="tab"><a id="tab_link_2">Posts</a></li> <li class="tab"><a id="tab_link_3">Tags</a></li> </ul> </li>
We make a list, we check it twice, we move on. This will be the navigation pane for the widget tabs. Simple stuff, but note that the initial list element is still open.
<div id="tab_div_1" class="selected_tab">
<ul>
comment_ID); //ID of comment
$use_id = $this_comment->comment_post_ID; //ID of post for comment
$this_post = get_post($use_id); //Get post
$post_title = $this_post->post_title; //get post title
$post_link = get_permalink($this_post->ID); //get post link
?>
<li> <!--output the comment link, number-->
<a class="detail clearfix" href="<?php echo $post_link ?>#comment-<?php echo $recent_comment->comment_ID; ?>">
<!--output actual comment text, excerpt-->
<span class="the-comment">
comment_content, 0, 55); ?>...
</span>
</a></li>
</ul>
</div>
So here is our first tab! This will also be the default starting tab, as you see the class of selected_tab applied to it here. Begin with an unordered list and then jump into PHP using the $recent_comments variable we just made. I left comments there so you can see what happens where. We iterate through each comment for the number specified, and store its related data. Then create a list item for each comment where all this fancy stuff says to display the link to the relevant comment, and output the text of the comment. Up to the first 55 characters. Shall we break it down a little further? Ok. Take everything inside of the list element, it is like seven lines wow. But once all the PHP has run, you will have about 55 characters of text that is clickable, and links to the comment itself. The link in XML would look something like this,
<a class="detail clearfix" href="linkToComment/#comment-228"> <span class="the-comment"> et netus et malesuada fames ac turpis egestas. Vestibulum </span> </a>
Hey guess what? That was tab number 1. Done. BAM! Time for number two,
<div id="tab_div_2" class="selected_tab no_display">
<ul>
have_posts()) : $tab_posts ->the_post();
setup_postdata($post);
$this_post = get_post($tab_posts->ID);
$link = get_permalink($this_post->ID);
?>
<li>
<a class="detail clearfix" href="<?php echo $link; ?>">
<span class="the-comment">
<span class="date">post_date)); ?></span>
</span>
</a></li>
</ul>
</div>
Here is where we use our custom query string from earlier. We start a modified version of the infamous WordPress Loop that runs until it is done displaying what it was told to, in our case, it will go through every post until it reaches the number we sent into it. Again, try not to get hunbg up on the funky stuff in here, the PHP echo’s (displays) the link again, that we use the WordPress functions to print the post title and date of the post. A lot of hoopla for a few sentences.
Tab three, here we come.
<div id="tab_div_3" class="selected_tab no_display">
</div>
<a href="http://www.thatryan.com/wp-content/uploads/2010/04/tags.jpg"><img class="aligncenter size-thumbnail wp-image-838" title="tags" src="http://www.thatryan.com/wp-content/uploads/2010/04/tags-150x150.jpg" alt="" width="150" height="150" /></a>
Yeah that is it, tab three rules! Because we use the WordPress tag cloud function, most of this is taken care of for us. So we call it with arguments specifying the size min and max that we want the tags to be. Then do not forget to close out the bracket, because this marks the end of the <em>widget</em> function.
Next in the list of what to build would be the update function but if you recall, we don't have to do anything to it, sweet. Moving on we come to the form function for our widget. Here we will build the display user see in the sidebar area where you drag your widget to activate it. Before pasting this next step in, either remove the skeleton code from the line <em>function form($instance) { </em> and below, (like the code directly under this paragraph below) or pay close attention when overwriting. This is because, the generic skeleton I had you put in earlier does not take into account the face that we are adding a form in here, so the brackets wont match and the world may explode!
[html] function form($instance) {
}
}
add_action('widgets_init', create_function('', 'return register_widget("tabbed_box");'));
?>
Ok now we are safe from broken brackets, paste in this code as we begin by creating the variables we used up above,(Yes I know the order is illogical, but hey),
function form($instance) {
$title = esc_attr($instance["title"]);
$comment_count = esc_attr($instance["comment_count"]);
$post_count = esc_attr($instance["post_count"]);
?>
You already know what happens here, we did this above right? Yup! We just create the variables and store what was input from the form. Now we build the actual form itself,
<label for="<?php echo $this->get_field_id('title'); ?>">
<input id="<?php echo $this->get_field_id('title'); ?>" class="widefat" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</label>
<label for="<?php echo $this->get_field_id('comment_count'); ?>">Comment Count</label>
<select id="<?php echo $this->get_field_id('comment_count'); ?>" class="widefat" name="<?php echo $this->get_field_name('comment_count'); ?>" size="1">
<option>selected="selected" value=""></option>
</select>
<label for="<?php echo $this->get_field_id('post_count'); ?>">Post Count</label>
<select id="<?php echo $this->get_field_id('post_count'); ?>" class="widefat" name="<?php echo $this->get_field_name('post_count'); ?>" size="1">
<option>selected="selected" value=""></option>
</select>

Trust me, I know it is ugly looking. This will display three fields, one a text entry for the optional title of the widget, and two drop down menus to select the number of comments and posts to display. The top one is the text field, made scary by using PHP to dynamically populate ID’s and variables. These are all inside a function named form, that takes an argument of $instance which if you remember, is our widget object. This is how our variables can retrieve the field data with a call such as $title = $instance["title"]. The following two fields create the drop downs, and uses a for loop to populate the selection list.
Finally add this at the very end, below what we just put into the file,
This closes the form function and then adds our widget to WordPress, then finally closes out our widget function.
A Little Style
The hard part is over, and you are still here! Well done. Now we are going to create some basic CSS to make this function proper, you will no doubt modify this to meet your theme requirement, but here is a base to go on,
/*lose the dots*/
ul,li{list-style:none;}
.no_display{display:none;}
/*surround entire widget */
li.tabbed_box{width:250px;background:#fff;font-size:9pt;}
/*style the navigation tabs*/
ul.box_tabs li{float:left;padding:0px;margin:0px;position:relative;z-index:2;}
ul.box_tabs li a{display:block;padding:10px 10px 20px;margin:0 10px;font-size:14px;color:#555;outline:none;}
ul.box_tabs li a:hover,ul.box_tabs li a:active,ul.box_tabs li.selected a{color:#999;text-decoration:none;}
/*style the content divs*/
.selected_tab{clear:both;position:relative;top:-8px;z-index:1;background:#fff;color:#555;}
.selected_tab a{color:#333;text-decoration:none;}
.selected_tab a:hover{color:#e9e9e9;}
.selected_tab ul {width:230px;margin-left:10px;}
.selected_tab ul li{color:#111;}
.selected_tab ul li a{display:block;padding:0px;text-decoration:none;}
.selected_tab ul li a:hover{text-decoration:none;background:#f8f8f8;}
.selected_tab ul li a span{float:left;display:block;line-height:20px;color:#333;border-bottom:1px solid #333;}
.selected_tab ul li a span.date{border:none;color:#777;}
.selected_tab ul li a span:hover{color:#666;}
That is just some basic styles, giving some width parameters to contain this beast and a little decoration to see what is going on. Moving on.
More PHP
WordPress has a magic file named functions.php, go ahead and find it in your themes root folder, and open it up. Here we will tell WordPress that our widget exists, and that it can use it. Somewhere in the file, place this,
include_once (TEMPLATEPATH."/tabbed_box.php");
This is saying that I put my widget file into my theme root folder, ie: sitting next to the functions.php file. If you put it somewhere else, adjust the file path to compensate. We are also going to take this opportunity to make sure jQuery is loaded, The Right Way. So if you happen to see this exact code in your functions.php file, then ignore this step, otherwise paste this in,
if ( !is_admin() ) {
wp_deregister_script('jquery');
wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"), false);
wp_enqueue_script('jquery');
}
This tells WordPress that we are in command! If jQuery is loaded, chuck it and use ours, ensuring that the library is loaded only once. Now be sure to save the file and close it up. Only one more to go!
jQuery Fun
Now what you ask? The fun stuff! Time to make this sucker move gracefully. So create a new file and name it something, how about tabbed.js and drop in this nonsense,
$(document).ready(function(){
$.current_tab = 1;
$("a[id^='tab_link_']").click(function()
{
$old_href_id = "#tab_link_"+$.current_tab;
$old_tab_id = "#tab_div_"+$.current_tab;
$($old_tab_id).slideUp("slow");
$($old_href_id).parent().removeClass("selected");
$use_id = $(this).attr("id").replace("tab_link_", "");
$new_tab_id = "#tab_div_"+$use_id;
$(this).parent().addClass("selected");
$($new_tab_id).slideDown("slow");
$.current_tab = $use_id;
return false;
});
});
Here is what is happening: Upon being ready a variable is created to keep track of what tab is being used. Then create a listener for when a tab is clicked, this matches the ID of the tabs, so the names we made in CSS are important
Once we click on a tab, we temporarily name two variables to hold the ID current tabs href attribute and which div it is, so we can know what to move. Then tell jQuery to slide the current tab up and out of the way, and remove the class selected (remember that we initially assigned the class of selected to the first tab). $this refers to the tab we clicked, meaning, the tab we want to go to. So we grab the first part of its current ID attribute and blank it out, leaving only the number. Then assign a fresh new ID with the number from the link to what our new current tab will be. So, if you click on the first tab, that tab has an id of tab_link_1 and this line replaces tab_link_1 with simply the number 1, in essence, erasing the first nine characters. This leaves us the ability to make the new tab have an ID of tab_div_1. I hope that makes sense.
Next we add the selected class to the new parent, which is the list item holding our tab, and tell our new chosen tab div to slide down to appear. We then update the current tab and return, watching the magic happen!
Are we done now? Not quite, one tiny final step before you can witness what you just build. We need to tell WordPress that we are using this script. So save it and put it into a folder in your theme root named “js” or something like that. Open up header.php and paste this into the section, underneath
<script src="<?php bloginfo('template_url'); ?"><!--mce:0--></script>
Ok, believe it or not, we are done. Time to make sure you put the files where they go, hop into your admin area and check out your new widget! Drag it into a sidebar pane and view the fun action. I hope you found this helpful, please leave a comment, suggestions for future tuts are always welcome too! Thanks for stopping by.
You can see a demo in action here! Though it is just a dummy site I put the widget on,

Social comments and analytics for this post…
This post was mentioned on Twitter by ryanolson: Hey guys, new #tutorial is up! How to build a #jquery powered tab widget for #wordpress! http://bit.ly/dD2AoV PLS RT!…
[...] to build a jQuery powered tabbed widget area for your WordPress blog.View full post on wordpress – Google Blog SearchRelated posts:17 Most Used WordPress Jquery PluginsWeb sites easy to build with wizardsWordPress [...]
[...] See more here: Build a jQuery Tabbed Widget for WordPress | thatryan [...]
[...] Read more here: Build a jQuery Tabbed Widget for WordPress | thatryan [...]
[...] here to see the original: Build a jQuery Tabbed Widget for WordPress | thatryan Tags: ?, [...]
[...] Build a jQuery Tabbed Widget for WordPress | thatryan [...]
[...] Read the rest here: Build a jQuery Tabbed Widget for WordPress | thatryan [...]
[...] Build a jQuery Tabbed Widget for WordPress | thatryan [...]
[...] Build a jQuery Tabbed Widget for WordPress | thatryan [...]
[...] Build a jQuery Tabbed Widget fοr WordPress | thatryan [...]
[...] original here: Build a jQuery Tabbed Widget for WordPress | thatryan If you enjoyed this article please consider sharing [...]
Demo don’t work : Forbidden
You don’t have permission to access /wordpress_demos/ on this server.
Apache/2.0.54 Server at demos.thatryan.com Port 80