phpwordpresscustom-wordpress-pageswpmu

wordpress wp_insert_post adds page to the menu


Im adding some pages in my WordPress project programatically. To do so I am using the wp_insert_post() function. This works great, however. The pages will automatically be added to the menu. For some of them that is good but one of the added pages I don't want in there.

Is there a way to prevent this without removing it manually. I was thinking of removing it from the menu after creating the page, but I don't really know how and maybe there is a better/easier way to do so ?

My code for creating the page is:

    $inschrijfbevestiging = array(
        'post_title'   => 'Inschrijfbevestiging',
        'post_content' => '[inschrijfbevestiging]',
        'post_status'  => 'publish',
        'post_type'    => 'page'
    );
    wp_insert_post($inschrijfbevestiging);

Solution

  • When this happens automatically, you can remove it from the menu after making the page:

    $objectWithPage = get_page_by_path('pageslug');
    $menu_item_ids = wp_get_associated_nav_menu_items( $objectWithPage->ID, 'post_type' );
    
    foreach ( (array) $menu_item_ids as $menu_item_id ) {
        wp_delete_post( $menu_item_id, true );
    }