Spice up your WordPress theme with jQuery

by Cristian Antohe. 44 Comments -

As Wordpress themes become more complex, we found our self trying to improve the user interaction on our web-site. Among a lot of things one can do, using Javascript is probably the most eye catching of them all. This is where jQuery steps up!

Before we start we need to know a few things about jQuery and WordPress.

First of all jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. In the last few years it has grown beyond a framework to become synonymous with JavaScript it self. To be honest I don’t know the last time I wrote JS code without the use of jQuery.

Another thing we need to know is that WordPress comes already packed with the latest jQuery and you can insert it inside your theme using a simple template tag. To do this we need to add the following code inside the functions.php file.

<?php
function insert_jquery(){
   wp_enqueue_script('jquery');
}
add_filter('wp_head','insert_jquery');
?>

Another way to do this would be to insert <?php wp_enqueue_script(‘jquery’); ?> inside your header.php template file before the <body> tag. I prefer the functions.php way and all of the next code spinets will basically be inserted using the same way.

Highlight Search Terms

A cool way to improve the usability of your WordPress search is to highlight the search terms using a bit of css and jquery.

Copy paste this code inside functions.php after the wp_enqueue_script(‘jquery’); code.

function highlight_search() {
		if (preg_match_all('/([^\s"\']+)|"([^"]*)"|\'([^\']*)\'/', get_search_query(), $terms)) {
			$terms = $terms[0];
		} else {
			return;
		}

		if(count($terms) > 0){
			$filtered_terms = array();

			foreach($terms as $term){
				//$term = attribute_escape(trim($this->remove_quotes($term)));
				if ( !empty($term) ){
					$filtered_terms[] = '"'.$term.'"';
				}
			}	

			if (count($filtered_terms) > 0) {
				echo '
				  <script type="text/javascript">
				    var hls_terms  = new Array('.implode(', ', $filtered_terms).');

				  </script>
				';
			}
		}
?>
<style type="text/css" media="screen">
  .hls { background: #eeeee7; } /* <- Change the CSS style of */
                                /*    highlighted texts here. */
</style>
<script type="text/javascript">
  jQuery.fn.extend({
    highlight: function(search, insensitive, css_class){
      var regex = new RegExp("(<[^>]*>)|(\\b"+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1") +")", insensitive ? "ig" : "g");
      return this.html(this.html().replace(regex, function(a, b, c){
        return (a.charAt(0) == "<") ? a : "<span class=\""+ css_class +"\">" + c + "</span>";
      }));
    }
  });
  jQuery(document).ready(function($){
  	if (window.hls_terms != undefined){
  		for (i in hls_terms){
    		$("#content").highlight(hls_terms[i], 1, "hls");
    	}
    }
  });
</script>

<?php
}

add_filter('wp_head', 'highlight_search');

Don’t forget to replace #content with the id or class of your content holder where the search results appear.

Source: Thaya Kareeson on How to Highlight Search Terms with jQuery

Animate your sidebar on hover

A nice effect is to animate your sidebar when you hover over it. Instead of the standard hover effect you get with css, we’ll use jQuery, the Easing and Color plugin for it to change the background color of your sidebar elements. The effect is similar to that found on WooThemes Blog.

First you need to download the Easing plugin and the Color plugin and put them inside your theme folder. We’ll also include them in our code for this to work.

function nice_sidebar(){
?>
<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/easing.js"></script>
<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/color.js"></script>
<script type="text/javascript">

jQuery(document).ready(function(){
    jQuery.easing.def = "easeInOutSine"; 

     jQuery('.aside > ul > li > ul > li').bind('mouseenter',function(){

      jQuery(this).stop().animate({
            backgroundColor: "#b5b5b5" }, 200)

    }).bind('mouseleave',function(){

        jQuery(this).stop().animate({
            backgroundColor: "#ffffff" }, 500)
    });

  });
</script>

<?php
}
add_filter('wp_head', 'nice_sidebar');

Note where it says .aside > ul > li > ul > li. That’s what we’re targeting and it will change based on your theme.

Remove “Title” Attributes From wp_list_categories & wp_list_pages

The title tags for your menu are displayed by showing a little label when hovered. The problem is that in some browsers your drop down menu will hide when you move your cursor over the tool tip, so it creates accessibility problems.

The best way to fix this problem is using jQuery because the title tags will still be there inside the XHTML for SEO purposes.

//Remove alt tags for the menu using javascript
function remove_alt(){
	wp_enqueue_script('jquery');
?>
<script type="text/javascript">

        jQuery(document).ready(function(){

                jQuery("li.cat-item a").each(function(){
                    jQuery(this).removeAttr('title');
                })                
                
                jQuery("li.page_item a").each(function(){
                    jQuery(this).removeAttr('title');
                })

        });
 
</script>
<?php
}
add_filter('wp_head','remove_alt');

Source: Foxinni on Remove Title Attributes From wp_list_categories & wp_list_pages Plugin

Multiple content columns for your blog posts and pages

Until we get native CSS support for multi-column newspaper-style layouts, our choices are limited to static column markup (basically adding 2-3 divs with a width and float them to the left or right). There are problems with this:

  • Text doesn’t wrap from column to column
  • Images and tables can’t easily span multiple columns

Luckily there is a solution in the form of a plugin: The Columnizer jQuery Plugin

So to make this work we first need to download the plugin and upload in inside our theme folder.


function multi_columns(){
?>
<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/autocolumn.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){

	jQuery('li').addClass("dontsplit");  
	jQuery('.entry-content').columnize({width:300});  

  });
</script>

<?php
}
add_filter('wp_head', 'multi_columns');

So a little bit of explaining here: the first line keep list items from being chopped in half like paragraphs can be. The second line columnizes the content! That’s it!

Also you can style your columns however you wish. Columnizer adds the following classes to the column divs it creates: .first.column .last.column .column

Conclusions

There are a lot of things one can do to spice up it’s WordPress theme using jQuery. Some things that I didn’t include here are tabbed widgets or collapsible categories, but most of those are available using a WordPress plugin anyway. Hopefully more and more functionality like this will be included into plugins in the future!