I’m trying to remove the entire <a>
tag from a menu item with a specific class.
<ul>
<li><a href="whatever">Whatever</li>
<li class="remove-link"><a href="whatever">Whatever</a></li>
<li><a href="whatever">Whatever</li>
<ul>
Would generate
<ul>
<li><a href="whatever">Whatever</li>
<li class="remove-link"></li>
<li><a href="whatever">Whatever</li>
</ul>
The code I am currently using removes the <a>
tag but not based on the class:
function remove_links( $menu ) {
return str_replace( '<a href="whatever">Whatever</a>', '', $menu );
}
add_filter( 'wp_nav_menu_items', 'remove_links' );
3
Answers
I don’t know much about WordPress but in pure JavaScript this can be done by this code –
Have a look
I agree that it seems like this makes more sense to do in JS. But if you you want to do it with PHP with your existing function, it looks like you’re only missing the li with the class there.
So change
return str_replace( '<a href="whatever">Whatever</a>', '', $menu );
to
return str_replace( '<li class="remove-link"><a href="whatever">Whatever</a></li>', '<li class="remove-link"></li>', $menu );
The code will look like this:
Here you need to understand a few things:
$args->theme_location == 'menu_1'
check, so we don’t destroy all the menus. we check the menu location and if matches then we do our job.<li>
tag.<a>
tag and its content with an empty string using regex and store it in an array, if the match fails then we don’t replace anything and store the line into an array.