JavaScript: change WordPress permalinks on internal links

JavaScript: change WordPress permalinks on internal links

How to replace the old URLs of your WordPress internal links with the new permalink structure by using JavaScript.

If you have recently changed your WordPress permalink structure, it's likely that all the internal links pointing to your old posts will return the infamous 404 error. Fortunately, JavaScript comes to the rescue with a lightweight and simple solution.

If your old permalink structure was like %year%/%monthnum%/%postname%/ and now is simply %postname%, you can use regular expressions to replace the old instances of such URLs with the new ones:


var changePermalinks = function() {
		var a = document.getElementsByTagName('a'),
			// change the base URL of the regular expression with your base URL
			oldPattern = /http:\/\/blog\.gabrieleromanato\.com\/([0-9]{4})\/([0-9]{2})\/(.*)/g,
			len = a.length,
			i;
		for (i = 0; i < len; i++) {
			var link = a[i];
			var url = link.href;
			if (oldPattern.test(url)) {
				link.setAttribute('href', url.replace(oldPattern, 'http://blog.gabrieleromanato.com/$3'));
			}
		}
	};

[view-example url="http://jsfiddle.net/gabrieleromanato/M2rnr/"]