I want to remove automatically the Home menu item, but only once, more precisely at the first run of WordPress or at the first child theme activation/loading. Now I have a function in the functions.php of my child theme that checks if the Home menu item exists and delete it from the menu. Of course, this function runs every time when WordPress loads. How to make it to run only once? I tried the add_filter_once() function, but I got only a PHP Fatal error: Call to undefined function add_filter_once().

function filter_wp_nav_menu_objects( $sorted_menu_items, $args ) { 

    foreach( $sorted_menu_items as $data ) {
        if ( in_array( "menu-item-home", $data->classes ) ) {
            wp_delete_post( $data->ID );
        }
    }

    return $sorted_menu_items;
} 

add_filter( 'wp_nav_menu_objects', 'filter_wp_nav_menu_objects', 10, 2 );

2 Answers
2

There is no native WordPress hook called add_filter_once(). This is an custom solution which will help you to run your hook only once.

For example if inside a loop or whatever situation you are facing. However,
The basic idea is to check when you need to stop using your hook and simply remove_hook from WordPress and once all done, you need to registere it again.

example code:

function add_filter_once( $hook, $callback, $priority = 10, $args = 1 ) {
    $singular = function () use ( $hook, $callback, $priority, $args, &$singular ) {
        call_user_func_array( $callback, func_get_args() );
        remove_filter( $hook, $singular, $priority );
    };

    return add_filter( $hook, $singular, $priority, $args );
}

The best way to understand what I try to explain to visit this link

Leave a Reply

Your email address will not be published. Required fields are marked *