0

I am looking to add the option of adding an anchor to my page in the Menu's page.

By default, the link has the Navigation Label with the link to the page, a Remove and a Cancel link. However, I need to add a page with a named anchor. So far, I've added all my links with Custom Links, but I would prefer being able to add my page in case my slug changes.

Is this possible via functions.php, or perhaps a plugin?

2 Answers 2

3

There's a specific filter for each nav item's attributes: nav_menu_link_attributes.

So, you can put in your functions.php file something like:

function mysite_add_anchor( $atts, $item, $args ) {

    $atts['href'] .= ( !empty( $item->xfn ) ? '#' . $item->xfn : '' );

    return $atts;

}

add_filter( 'nav_menu_link_attributes', 'mysite_add_anchor', 10, 3 );

What this does, is check the Link Relationship (XFN), and if it's not empty, it will add that to the end of your link with the #.

A couple things, if you don't see "Link Relationship" in the menu item, check the "Screen Options" at the top and check the box. ALSO, you can use almost any of the other properties you aren't currently using for Advanced Menu Properties.

https://codex.wordpress.org/Appearance_Menus_Screen

Not sure if Link Relationship isn't the right one, but it's the one I use the least.

Note: I didn't test the code.

0

Custom links are the easiest solution, you can always modify the menu when you modify the slug. And yes this can be made into a plugin (or your theme's functions.php file), maybe you could have a checbox on the post/page editing screen that changes the behaviour of the page link so that example.com/some-page would becode example.com/#some-page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.