Practical uses of jQuery in WordPress

Practical uses of jQuery in WordPress

Some common use cases of jQuery in WordPress development.

I usually spend most of my time by tweaking and fixing several rendering inconsistencies created by many WordPress themes and plugins. I've noticed that the overwhelming majority of these bugs can be fixed by manipulating the DOM of web documents without the need to modify the underlying HTML and PHP code but simply by using jQuery in an appropriate manner.

Removing unwanted elements

Removing unwanted elements from WordPress posts and pages is surely the most required task. It basically involves the use of the .remove() method together with the selector's context.


// Removing empty p's and line-breaks

$('p:empty, br', '.post').remove();

// Removing the first image from a post/page

var $firstImage = $('img:first', '.post');
if($firstImage.length) {
	$firstImage.remove();
}

// Removing paragraphs around shortcode's markup

$('div.my-shortcode-class', '.post').each(function() {
	var $shortcode = $(this);
	var $parent = $shortcode.parent();
	
	if($parent.is('p')) {
		var replacement = '<div class="my-shortcode-class">' + $shortcode.html() + '</div>';
		$parent.replaceWith(replacement);
		
	}
});

The latter solution is more elaborated and requires an extended DOM manipulation to properly replace all the instances of the surrounding paragraphs around shortcodes with the correct markup structure.

Executing actions on specific sections

WordPress adds several CSS classes to the body element via the body_class() function. These classes reflect the current hierarchy of your WordPress theme.

For example, on the home page the markup structure is similar to the following:


<body class="home blog logged-in">

On a single post, instead, results are different:


<body class="single single-post postid-1234 single-format-standard logged-in">

We can use these classes to execute specific actions on specific sections of a WordPress site by defining an utility object.


// Specific WP methods
if (typeof $.WP === 'undefined') {
	$.WP = {
		isHome: function() {
			if (!$('body').hasClass('home')) {
				return false;
				
			}
			return true;
			
		},
		isSingle: function() {
			if (!$('body').hasClass('single')) {
				return false;
				
			}
			return true;
			
		},
		isPage: function() {
			if (!$('body').hasClass('page')) {
				return false;
				
			}
			return true;
			
		},
		isCategory: function() {
			if (!$('body').hasClass('category')) {
				return false;
				
			}
			return true;
			
		},
		isTag: function() {
			if (!$('body').hasClass('tag')) {
				return false;
				
			}
			return true;
			
		},
		isArchive: function() {
			if (!$('body').hasClass('archive')) {
				return false;
				
			}
			return true;
			
		},
		is404: function() {
			if (!$('body').hasClass('error404')) {
				return false;
				
			}
			return true;

			
		},
		isLoggedIn: function() {
			if (!$('body').hasClass('logged-in')) {
				return false;
				
			}
			return true;
			
		},
		isPaged: function() {
			var url = location.href;
			if (/\/page\//.test(url) || /page\?/.test(url)) {
				return true;
				
			}
			return false;

			
		},
		isSearch: function() {
			if (!$('body').hasClass('search')) {
				return false;
				
			}
			return true;

			
		},
		isCustomSection: function(name) {
			if (!$('body').hasClass(name)) {
				return false;
				
			}
			return true;
			
		},
		isAdmin: function() {
			if (!$('body').hasClass('wp-admin')) {
				return false;
				
			}
			return true;
			
		},
		isThemeOptionsPage: function(slug) {
			var body = $('body')[0];
			var bodyClasses = body.className;
			if (bodyClasses.indexOf(slug) != -1) {
				return true;
				
			}
			return false;
			
		}
		
	};
	
}

Now we can run our code when it's actually needed, for example on a page or on the homepage:


if($.WP.isHome()) {
	// code for the homepage
}

Overriding existing plugin's actions

Usually a WordPress installation can be augmented with several plugins which add new features and functionalities to your site. From time to time a site owner can decide to modify an existing plugin because its default actions don't satisfy the new requirements of the website.

Suppose that you have a lightbox plugin whose default action on the click must me radically changed. Instead of wasting your time by studying the plugin's code, you can simply override its default action on the targeted elements:


$('a.lightbox').off('click'); // Remove the event handler
$('a.lightbox').on('click', handler);  // Override with your own handler

AJAX navigation without WordPress plugins

A navigation menu can be enhanced by using AJAX. The trick to make this solution work on your WordPress site is to keep a consistent document structure across your pages.

If you have a navigation menu where each link points to a different page, you can add AJAX to this menu in a simple way:


(function($) {
	$.fn.ajaxNavigation = function(options) {
		var settings = {
			remoteTarget: '#page',
			localTarget: '#content',
			ajaxWrapper: 'ajax-wrapper',
			animationSpeed: 500
		};
		options = $.extend(settings, options);
		
		return this.each(function() {
			var $element = $(this);
			var $wrapper = $('<div id="' + options.ajaxWrapper + '"/>');
			$wrapper.appendTo(options.localTarget);
			
			$('a', $element).on('click', function(event) {
				event.preventDefault();
				var url = $(this).attr('href');
				var $target = $('#' + options.ajaxWrapper + "'");
				$target.empty().load(url + ' ' + options.remoteTarget, function() {
					$('html, body').animate({
						scrollTop: $target.offset().top
					}, options.animationSpeed);
				
				});
			
			});
			
		
		});
	};

})(jQuery);

The remoteTarget option is the selector that matches the main container of the page you want to fetch. Bear in mind that the .load() method will simply grab the remote HTML structure without cloning CSS styles or JavaScript events. If you want to execute further actions on the newly inserted DOM structure, you have to use the callback function of the AJAX method.

Passing HTML validation even when using nonstandard markup

If you use iframes to embed videos from YouTube or Vimeo, you'll probably get several validation errors because of the nonstandard HTML structure used by the embed code.

To fix this problem, you can use jQuery to add the required markup without invalidating your documents:


$('iframe', '.post').attr('frameborder', '0');

If you want to be more specific, you can run a search to find only a subset of these elements:


$('iframe', '.post').each(function() {
	var $iframe = $(this);
	var src = $iframe.attr('src');
	var videoReg = /vimeo|youtube/g;
	if(videoReg.test(src)) {
		$iframe.attr('frameborder', '0');
	}
});

Changing the DOM structure

Sometimes we need to rearrange our page elements to fit the needs of a new layout or redesign. If our goal is to simply display elements differently, then we can use jQuery to manipulate the DOM structure:


// Inserts the navigation bar after the header
var $header = $('#header');
var $navigation = $('#navigation');
var $navCopy = $navigation.clone();
$($navCopy).insertAfter($header);
$navigation.remove();

We've simply cloned the original element, inserted its copy into the DOM and then removed the original element.

Conclusions

These are just a few of the possible use cases of jQuery in WordPress. You'll surely find more ways and approaches as you face new challenges when developing WordPress sites.