WordPress: How to remove unwanted hash or other characters from WordPress page URL

In this quick tutorial, we will learn how to remove unwanted hashes, special characters, query variable parameters or any other type of text, from your WordPress page URL.

Remember that hashes are often added for a good reason, such as when switching tabs with JavaScript or when jumping from a section of the view-port to another through elements id attributes.. But if you really want to remove that, or you have specific character you want to eliminate, then, keep reading.

Now, you’ll have to think, whether this unwanted character is being placed on page load, or frequently after the page is loaded.

On page load:

Just add the following snippet to the bottom of your child theme functions file, or using a custom plugin. But, remember the add the targeted character within the variable inside the function:

$target = '#hash';

(for this, it will remove everything following #hash in the page url. Make it a hash (#stuff), or a query variable (?query=) or whatever fits your needs.

 

This is the code:

// replace #hash with your target character
add_action('wp_footer', function() {
	$target = '#hash';
	?>
		<script type="text/javascript">
		window.onload = function() {
		    var pageurl = window.location.href;
		    if( pageurl.indexOf('<?php echo $target; ?>') > 0 ) {
				var flush = pageurl.substring(0, pageurl.indexOf('<?php echo $target; ?>'));				
				window.history.replaceState( null, null, flush );
			}
		}
		</script>
	<?php
});

Frequently after page load:

For this one, we’ll set an interval to do the function repeatedly in order to verify whether our page URL is clean or not, from those unwanted characters:

// replace #hash with your target character, and $interval with number of milliseconds (1s = 1000 ms)
add_action('wp_footer', function() {
	$target = '#hash';
	$interval = '400';
	?>
		<script type="text/javascript">
		window.onload = function() {
			window.setInterval(function () {
			    var pageurl = window.location.href;
			    if( pageurl.indexOf('<?php echo $target; ?>') > 0 ) {
					var flush = pageurl.substring(0, pageurl.indexOf('<?php echo $target; ?>'));				
					window.history.replaceState( null, null, flush );
				}
			}, <?php echo $interval; ?>);
		}
		</script>
	<?php
});
Digital Ocean

Cheap Cloud SSD Hosting

Get a VPS now starting at $5/m, fast and perfect for WordPress and PHP applications

Sign Up with $10 Credit