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!

 

21 Comments

  1. NotAlame
    Posted August 3, 2009 at 6:14 pm | Permalink

    Thanks a lot!
    Very useful!

  2. Posted August 3, 2009 at 6:18 pm | Permalink

    Really nice jQuery tricks!

  3. Posted August 3, 2009 at 9:14 pm | Permalink

    Good ideas. I will try them out, especially the columns idea. A good way to separate content from layout.

    A couple of thoughts:
    1. I’ve always been intimidated of editing functions.php for fear of breaking WP or something silly like that. This will get me started down the right path.
    2. I guess I knew jQuery was included, but I always find myself linking to the Google code files. Thoughts on which one is a better approach? And is there a way to link to the Google files using functions.php?

    Thanks again!

  4. Posted August 3, 2009 at 10:28 pm | Permalink

    I really need to try the multiple content columns, it’s really a cool trick.

  5. Posted August 4, 2009 at 12:06 am | Permalink

    Very cool jQuery tricks. I need to look into Columnizer more.

    Thanks!

  6. Posted August 4, 2009 at 3:11 am | Permalink

    Good tricks, I recommend deregistering WP’s jQuery file and linking to Google-hosted one. Even jQuery.com does that, you can’t fault the master Resig!

  7. Posted August 4, 2009 at 5:36 am | Permalink

    Thanks, these are really useful.

  8. Posted August 4, 2009 at 10:27 am | Permalink

    Thanks for this guide, very useful indeed

  9. Danny G Smith
    Posted August 4, 2009 at 4:51 pm | Permalink

    So, we don’t install the columnizer plugin, but use the autocolumn.min.js file only? I could not get the plugin to install.

  10. Posted August 5, 2009 at 1:59 pm | Permalink

    Thanks A lot..Very useful!

  11. Posted August 6, 2009 at 8:21 am | Permalink

    Thanks for the information i was struggling to get this type of information helped me a lot thanks again

  12. Posted August 10, 2009 at 3:10 pm | Permalink

    Thanks for the tutorial, it;s really helpfull.

    From

    David

  13. Posted August 10, 2009 at 4:20 pm | Permalink

    I had a question, is it posible to have random colors for the hovers, I mean that every li, ul has a different color random?

  14. Posted August 11, 2009 at 5:45 am | Permalink

    Wonderful!! very helpful! Thanks :)

  15. Posted August 14, 2009 at 12:21 pm | Permalink

    Thank you so much for your post here! This information very useful for me because I use wordpress for my blogs. This way I can simplify my works and save lots of time. Thanks!

  16. Posted September 4, 2009 at 2:42 pm | Permalink

    That “Remove Title Text” snippet is very useful, thanks for sharing ;)

  17. Posted September 5, 2009 at 3:17 pm | Permalink

    I am going to implement this on my blog. Hope it looks good.

  18. Posted September 9, 2009 at 11:38 pm | Permalink

    thank you very much for this useful post

  19. Posted December 21, 2009 at 6:23 pm | Permalink

    Thanks for the tips. I was looking for the right way to remove the title attribute from the navigation links in the Thesis theme. This is possible with a small modification/addition to your ‘Remove “Title” Attributes From wp_list_categories & wp_list_pages’ code. Just add the following jQuery functions after the “jQuery(document).ready(function(){” line:

    jQuery(”ul.menu li.tab a”).each(function(){
    jQuery(this).removeAttr(’title’);
    })
    jQuery(”ul.submenu li.tab a”).each(function(){
    jQuery(this).removeAttr(’title’);
    })

  20. Posted December 27, 2009 at 6:53 am | Permalink

    Great post . I must try now :)

  21. Posted June 1, 2010 at 11:33 am | Permalink

    This is very helpful. The codes are pretty simple but they brought out nice effects like animating the sidebar when you hover over it. Thank you for sharing.

21 Trackbacks

  1. [...] Spice up your WordPress theme with jQuery Share and Enjoy: [...]

  2. [...] the original here:  Spice up your WordPress theme with jQuery Share and [...]

  3. By Spice up your WordPress theme with jQuery on August 3, 2009 at 10:21 pm

    [...] here to see the original: Spice up your WordPress theme with jQuery SHARETHIS.addEntry({ title: "Spice up your WordPress theme with jQuery", url: [...]

  4. [...] Spice up your WordPress theme with jQuery 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! (tags: wordpress jquery) [...]

  5. [...] Spice up your WordPress theme with jQuerycatswhocode.com [...]

  6. [...] De The Top 100 Web Sites of 2009 – Reviews by PC Magazine Bodega: Your corner store for apps Spice up your WordPress theme with jQuery Free legal documents for entrepreneurs VentureBeat 100 Best Self-Education Sites for Switching [...]

  7. [...] De The Top 100 Web Sites of 2009 – Reviews by PC Magazine Bodega: Your corner store for apps Spice up your WordPress theme with jQuery Free legal documents for entrepreneurs VentureBeat 100 Best Self-Education Sites for Switching [...]

  8. By Links creativos para 03.08/04.08 | Eliseos.net on August 4, 2009 at 1:04 pm

    [...] Spice up your WordPress theme with jQuery [...]

  9. [...] See the rest here: Spice up your WordPress theme with jQuery [...]

  10. [...] Spice up your WordPress theme with jQuery [...]

  11. By Mejora tu Theme de WordPress usando jQuery on August 14, 2009 at 9:48 pm

    [...] Si te gustaría agregar un poco más de interacción o animación al Theme de WordPress en Cats who code encontré unos excelentes códigos que te pueden servir para lograr efectos [...]

  12. [...] Spice up your WordPress theme with jQuery [...]

  13. [...] Spice up your WordPress theme with jQuery [...]

  14. [...] • Spice up your WordPress theme with jQuery [...]

  15. By links for 2009-08-19 | Eric Reboisson's Blog on August 19, 2009 at 10:08 pm

    [...] Spice up your WordPress theme with jQuery (tags: wordpress jquery tutorial tips theme themes snippets template wordpress-themes) [...]

  16. [...] Spice up your WordPress theme with jQuery وسوم: jQuery, ووردبريس [...]

  17. [...] Spice up your WordPress theme with jQuery [...]

  18. [...] Spice up your WordPress theme with jQuery Und last but not least Magie mit jQuery innerhalb eines Wordpress-Themes. Und ja! Eigentlich nenne ich diesen Link nur, weil mir die Domain so gut gefällt! Wie wäre es mit der Domain programmierender-troll.de? :) [...]

  19. By 10 incredible JQuery navigation menus on September 7, 2009 at 7:25 pm

    [...] Spice up your WordPress theme with jQuery [...]

  20. [...] Mejora el theme de tu WordPress con jQuery – Cats who Code. [...]

  21. By 10 incredible JQuery navigation menus | meshdairy on October 29, 2009 at 9:09 am

    [...] Spice up your WordPress theme with jQuery [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting

  • Smashing Network
  • Hosted by VPS.net and Akamai CDN
WordPress Appliance - Powered by TurnKey Linux