Edit menu item title from edit page/post

Whenever you add a new item to WordPress Menu ( Appearance -> Menu ) it creates a new Post of Post Type nav_menu_item and gets assigned a post meta called _menu_item_object_id with the main Post ID.

For example, if I create a page called “Home” it gets assigned a Post ID of 2. Now, when I go to Menus and add the page to a menu, WordPress creates a new post of post type nav_menu_item, assigns the title to “Home”, gives it a ID in the database of 3 and assigns post meta _menu_item_object_id = 2. If we want to change the title to “Homepage” in Menus, it would change the Post ID 3 to title “Homepage”.

If we wanted to change the title via metabox we would need to find Post Type nav_menu_item that has post_meta _menu_item_object_id with the same ID as our current page. I’m assuming you already have a metabox setup, are checking post types, and nonces.

if( 'page' == $post->post_type ) {

    // Check Nonces

    $nav_item = new WP_Query( array(
        'post_type'      => 'nav_menu_item',        // Nav Post Type
        'posts_per_page' => 1,                      // We only expect 1 result, if any
        'meta_key'       => '_menu_item_object_id', // With our Meta Key
        'meta_value'     => $post->ID               // And our Correct Page
    ) );

    if( $nav_item->have_posts() ) {                 // Ensure something was found
        wp_update_post( array(                      // Update the `nav_menu_item` Post Title
            'ID'            => $nav_item->posts[0]->ID,
            'post_title'    => htmlspecialchars( sanitize_text_field( $_POST['_textbox_name'] ) )
        ) );
    }

    // Update Page Meta
}

At the end of the above code, you would also want to update the Pages post meta to the new title so you can re-display it in the metabox textbox which makes it easier for the user to update in the future.


Alternatively, if you want to update the metabox textbox whenever a user adds a new Item to the Menu you can reverse the process:

if( 'nav_menu_item' == $post->post_type ) {
    // Check Nonces

    $added_id   = get_post_meta( $post->ID, '_menu_item_object_id', true ); // This may or may not be a Page ID
    $type       = get_post_field( 'post_type', $added_id );

    if( 'page' == $type ) {
        // Update Page Metabox Textbox Here with `$post->post_title`
    }
}