0

Before the questions roll in... I am using Advanced Custom Fields to add a selection field in the menu items to select a font awesome icon which is added before the title. The coding works great except for one small issue. If you want to create a menu item say a home link with only an icon and leave the title blank wordpress got in their mind that it would be a good idea to delete the menu item if the title is blank.

I am looking for a way to modify the save menu function to prevent the deletion of the item containing a blank title. This would have to be a function that could reside within the functions.php file as it will be built into our premium theme.

1 Answer 1

0

It took me forever to find a solution to this. I thought I would release my code here for anyone that needs an answer to this question. I had to use two functions in order to solve the problem.

The first function replaces the blank label with   to prevent the deletion of the menu item.

add_action('wp_update_nav_menu', 'blank_menu_items');
function blank_menu_items($nav_menu_selected_id) {
    $navmenudata = json_decode(stripslashes($_POST['nav-menu-data']),true);
    $k=0;
    foreach((array) $navmenudata as $data){
        if(
           isset($data['name']) && 
           isset($data['value']) &&
           strpos($data['name'], 'menu-item-title') !==false
        ){
            if(trim($data['value']) == ''){
                $data['value'] = ' ';
                $navmenudata[$k] = $data;
            }
        }
        $k++;
    }
    if(isset($_POST['menu-item-title'])){
        $k=0;
        foreach($_POST['menu-item-title'] as $key => $value){
            if(trim($value) == ''){
                $value = ' ';
                $_POST['menu-item-title'][$key] = $value;
            }
            $k++;
        }
    }
}

This second function simply removes the   when the menu is rendered.

add_filter('wp_nav_menu_objects', 'blank_menu_display', 10, 2);
function blank_menu_display( $items, $args ){
    foreach( $items as &$item ) {
        $item->title = str_replace(' ','',$item->title);
    }
    return $items;
}

These were the basic functions and I did not include the ACF code to make it easier to understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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