Search code examples
wordpressmenunavigationpermalinks

Replace menu permalink/hyperlink with only menu name/slug in wordpress


I don't know if i am asking this correctly, but i will try. I am doing this for history pushstate purpose.

Code to get menu wihout ul and li:

$topmenu= array(
  'container'       => false,
  'echo'            => false,
  'items_wrap'      => '%3$s',
  'depth'           => 0
);

echo strip_tags(wp_nav_menu( $topmenu), '<a>');

At the moment, it gives mes only <a> tag with href as expected.

For example:

<a href="http://example.com/page1">Page 1</a>
<a href="http://example.com/page2">Page 2</a>
<a href="http://example.com/page3">Page 3</a>
// etc

My question:

How to disable/hide full permalink/hyperlink in href attribute, but keep showing page slug?

What i need for example:

<a href="/page1"></a>
// etc

I tryed to make this work to changing nav-menu-template.php, but i failed.

Thanks for any answers.


Solution

  • There's no need for building a navigation with wp_nav_menu then. If you just want to get the links of a navigation you've set up in your wordpress backend you need the name, id or slug of the navigation.

    You can get the nav_menu_items with

    $items = wp_get_nav_menu_items( 'name_of_your_navigation' );
    

    Now you need to remove the home_url from each item's url like so

    foreach ( $items as $item ) {
        $url = str_replace( home_url(), '', $item->url );
        echo '<a href="' . $url . '">' . $url . '</a>';
    }