Wordpress , local anchor instead of full link with wp_nav_menu

114 Views Asked by At

I'm trying to change the href to a local anchor. My idea was to use preg_replace to strip the home_url();

Instead of....

<a href="http://example.com/menu-item/">Menu Item</a>

...I'd like to create

<a href="#menu-item/">Menu Item</a>

My code so far:

$menu_one = wp_nav_menu(
array(
    'echo' => 0,
    'container' => false,
    'menu_class' => '',
    'menu_id' => '',
    'theme_location' => 'main-menu'
    )
);

//get home url
$homeurl = home_url();

$menu_one = preg_replace( $homeurl, '#', $menu_one );
echo '<ul id="main-menu">' . $menu_one . '</ul>';   

I currently get the error preg_replace(): Delimiter must not be alphanumeric or backslash; Any help would be appreciated (my php knowledge is quite limited and also maybe there is a more elegant way to do this)

1

There are 1 best solutions below

2
On

You need to make your $homeurl into a valid regex pattern by wrapping it in a delimiter like /$homeurl/.

Also, it is vital to escape some of the characters in the URL.

// Some characters must be "escaped" e.g the / must become \/.
$homeurl = preg_quote( $homeurl );

// Wrap the string in a delimiter that preg_replace expects:
$homeurl = "/$homeurl/";

// Now try it:
$menu_one = preg_replace( $homeurl, '#', $menu_one );