wordpress wp_insert_post adds page to the menu

320 Views Asked by At

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);
3

There are 3 best solutions below

0
On BEST ANSWER

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 );
}
3
On

This problem occurs when your menu not set before for one theme_location

You must set a menu to this theme_location so this never change automatically.

1
On

1.Login to the WordPress Dashboard.

2.From the 'Appearance' menu on the left-hand side of the Dashboard, select the 'Menus' option to bring up the Menu Editor.

3.Select Create a new menu at the top of the page

4.Enter a name for your new menu in the Menu Name box

5.Click the Create Menu button.

link: https://codex.wordpress.org/WordPress_Menu_User_Guide