skip to Main Content

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


  1. I don’t know much about WordPress but in pure JavaScript this can be done by this code –

    Have a look

    
    ...
    
    document.querySelector(".remove-link").innerHTML = "";
    
    ...
    
    
    Login or Signup to reply.
  2. 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 );

    Login or Signup to reply.
  3. The code will look like this:

    function cc_add_search_form( $items, $args ) {
        if ( $args->theme_location == 'menu_1' ) {
            $items_array     = explode( PHP_EOL, str_replace( "r", '', $items ) );
            $new_items_array = array();
            foreach ( $items_array as $line ) {
                if ( preg_match( '/<li[^>]*class="[^"]*bremove-linkb[^"]*"[^>]*>/i', $line ) ) {
                    $new_items_array[] = preg_replace( '/(<a[^>]*>.*?</a>)/is', '', $line );
                } else {
                    $new_items_array[] = $line;
                }
            }
    
            $items = trim( join( PHP_EOL, $new_items_array ) );
        }
    
        return $items;
    }
    add_filter( 'wp_nav_menu_items', 'cc_add_search_form', 10, 2 );
    

    Here you need to understand a few things:

    • code using $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.
    • we’re making an array for loop from the given items by splitting the contenting from EOL = END OF LINE
    • Then we loop and match the class in the <li> tag.
    • If a match is a success then we replace the <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.
    • at last, we again JOIN the lines by EOL and return the updated items.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search