Skip to content

Instantly share code, notes, and snippets.

@kmwalsh
Last active January 24, 2017 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmwalsh/abebb8d8a9d42e41f0ad893267d27008 to your computer and use it in GitHub Desktop.
Save kmwalsh/abebb8d8a9d42e41f0ad893267d27008 to your computer and use it in GitHub Desktop.
modify wordpress menu for anchor links in semi-single page site
/**
* modify primary menu so that the anchor links always point back to the homepage
*/
if( ! function_exists('nav_items') ) {
add_filter( 'wp_get_nav_menu_items','nav_items', 11, 3 );
function nav_items( $items, $menu, $args )
{
if( is_admin() )
return $items;
// check whether it's the homepage -- if anchor links are all on the homepage anyway, no need to modify
// also check whether it's our theme location -- change "primary" to your theme location
if ( ! is_home() && $menu->slug === 'primary')
foreach( $items as $item )
{
// get the end of the URL for use
$hash = $item->url;
if ( substr( $hash, 0, 1 ) === "#" )
// append the hash URL to the site URL (homepage where anchor links are)
$item->url = site_url() . $hash;
}
return $items;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment