One Page Anchors and Supporting Pages Menu

There’s a popular myth that in the 1960s, upon realizing regular pens would not function in space, NASA spent millions of dollars developing a pen that would work in zero gravity. The Russian answer to the same problem was to simply issue their cosmonauts with pencils.

Despite the fiction, the message is a valuable one: you don’t usually need to re-invent the wheel.

While working on a one-page site for a customer, I came across a problem. The menu was geared toward scrolling through anchors on the front page… but there was also an online shop (WooCommerce) which uses pages outside the single page design. This meant as soon as you left the home page and entered the shop, those menu items pointing to the front page anchors no longer worked.

I considered adding a second header menu that would replace the primary menu on anything other than the front page, spent some time looking through various plugin options (though I didn’t particularly want to go that route), and generally started to disappear down a rabbit hole in Google.

The answer to the problem had me kicking myself, because it was a simple one. I was so focused on a complicated solution that the simple answer hadn’t even occured to me: just insert the site url before the anchor hash in the menu for any pages outside the front page. Duh.

Insert the following code into your theme functions file:

function add_menu_item_url( $items, $args ) {
if( ! is_front_page() ) {
$items = str_replace( '#', site_url( '#' ), $items );
return $items;
add_filter( 'wp_nav_menu_items','add_menu_item_url', 10, 2 );

Original Post

Many thanks to Cockahoop Digital for reminding me that sometimes, I just need a pencil.