JavaScript: change WordPress permalinks on internal links

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/"]
Back to top