Skip to main content
Skip to article

How to make hash links work from other pages in WordPress

JS, tips
999 views

The common challenge with using a hash link in the main navigation to specific section in the home page, is getting it to work from other pages. You may get around this with a few hacks e.g. adding /#hashlink, but this jumps to the section without smooth scrolling while on the home page.

If you’re fine with this behavior, then nothing to worry about, but if you wish to retain the smooth scrolling on the home page, what we need is have the hash URL as simply ‘#hashlink’ on the homepage, but as ‘/#hashlink’ on other pages. We are going to use JavaScript to check if the current page is not the homepage, and change the URL from ‘#hashlink’ to ‘/#hashlink’. Please note that the hash link will jump to the section from other pages nonetheless.

Step 1 – Set up your menu with a class

Go over to the WordPress Menu and add a class of ‘hash’ to all menu links with a hash link.

if you can’t find the CSS Classes input, go to Screen Options and enable it

Step 2 – Add the following JavaScript to your code manager

If you’re using a custom menu/manual menu setup, replace the class .menu-item with the class of your custom menu.

var HomeHashLinks = document.querySelectorAll('.menu-item.hash a'),
     pageIsHome = document.body.classList.contains('home');


if (!pageIsHome){

		HomeHashLinks.forEach(HomeHashLink => {

		    var href = HomeHashLink.getAttribute("href");
		   // console.log(href)
		    var newHref = "/" + href;
		   // console.log(newHref)
		    HomeHashLink.setAttribute("href", newHref)
    
})

}
Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how Design with Cracka is funded, why it matters, and how you can support us.
Join the Community
Join over 7000 learners and contributors on Design with Cracka community. Don't miss out on the conversations!
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Leave a Reply

Your email address will not be published. Required fields are marked *

dicecartselectearthcrossarrow-rightlayerstext-align-center
0
Would love your thoughts, please comment.x
()
x