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!
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!
[...] Spice up your WordPress theme with jQuery Share and Enjoy: [...]
Thanks a lot!
Very useful!
Really nice jQuery tricks!
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!
[...] the original here:Â Spice up your WordPress theme with jQuery Share and [...]
[...] here to see the original: Spice up your WordPress theme with jQuery SHARETHIS.addEntry({ title: "Spice up your WordPress theme with jQuery", url: [...]
I really need to try the multiple content columns, it’s really a cool trick.
Very cool jQuery tricks. I need to look into Columnizer more.
Thanks!
[...] 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) [...]
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
masterResig!Thanks, these are really useful.
[...] Spice up your WordPress theme with jQuerycatswhocode.com [...]
Thanks for this guide, very useful indeed
[...] 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 [...]
[...] 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 [...]
[...] Spice up your WordPress theme with jQuery [...]
So, we don’t install the columnizer plugin, but use the autocolumn.min.js file only? I could not get the plugin to install.
Thanks A lot..Very useful!
Thanks for the information i was struggling to get this type of information helped me a lot thanks again
[...] See the rest here: Spice up your WordPress theme with jQuery [...]
Thanks for the tutorial, it;s really helpfull.
From
David
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?
Wonderful!! very helpful! Thanks
[...] Spice up your WordPress theme with jQuery [...]
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!
[...] 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 [...]
[...] Spice up your WordPress theme with jQuery [...]
[...] Spice up your WordPress theme with jQuery [...]
[...] • Spice up your WordPress theme with jQuery [...]
[...] Spice up your WordPress theme with jQuery (tags: wordpress jquery tutorial tips theme themes snippets template wordpress-themes) [...]
[...] Spice up your WordPress theme with jQuery وسوم: jQuery, ووردبريس [...]
[...] Spice up your WordPress theme with jQuery [...]
[...] 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?
[...]
That “Remove Title Text” snippet is very useful, thanks for sharing
I am going to implement this on my blog. Hope it looks good.
[...] Spice up your WordPress theme with jQuery [...]
thank you very much for this useful post
[...] Mejora el theme de tu WordPress con jQuery – Cats who Code. [...]
[...] Spice up your WordPress theme with jQuery [...]
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’);
})
Great post . I must try now
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.
thank you for the incredible details. i’m back to read more later.
I’m need to create a slide show in the header, if it is possible to use this Jquery ?