WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

On theme activation the following code doesn't create my menu with the 'New Page' item, the menu is created and the location is assigned to 'submenu' but no menu item of my newly created page?

What am I missing?

if (isset($_GET['activated']) && is_admin()){
    $new_page_title = 'New Page';
    $new_page_slug = '/new-page/';
    $new_page_content = 'This is the page content';
    $new_page_template = 'page-job-list.php'; //ex. template-custom.php. Leave blank if you don't want a custom page template.
    //don't change the code bellow, unless you know what you're doing
    $page_check = get_page_by_title($new_page_title);
    $new_page = array(
            'post_type' => 'page',
            'post_title' => $new_page_title,
            'post_content' => $new_page_content,
        'post_status' => 'publish',
        'post_author' => 1,
        $new_page_id = wp_insert_post($new_page);
                update_post_meta($new_page_id, '_wp_page_template', $new_page_template);

// Check if the menu exists
$menu_name = 'AnotherMenu';
$menu_exists = wp_get_nav_menu_object( $menu_name );

// If it doesn't exist, let's create it.
if( !$menu_exists){
    $menu_id = wp_create_nav_menu($menu_name);

    wp_update_nav_menu_item($menu_id, $new_page_id, array(
        'menu-item-title' =>  __($new_page_title),
        'menu-item-url' => home_url( $new_page_slug ), 
        'menu-item-status' => 'publish'));

$menulocation = 'submenu';

if(!has_nav_menu($menulocation) ){
    $locations = get_theme_mod('nav_menu_locations');
    $locations[$menulocation] = $menu_id;  //$foo is term_id of menu
    set_theme_mod('nav_menu_locations', $locations);
share|improve this question

The value of $menu_id is not initialized if the menu already exists. So, if on theme activation, $menu_exists is true, $menu_id will never be set to a value and this line should produce a PHP warning:

$locations[$menulocation] = $menu_id;

You could try adding it like this:

if ( $menu_exists ) {
    $menu_id = $menu_exists->term_id;

} else {
    // Menu doesn't exist, let's create it.
    $menu_id = wp_create_nav_menu( $menu_name );

    wp_update_nav_menu_item( $menu_id, $new_page_id, array(
        'menu-item-title' =>  __( $new_page_title ),
        'menu-item-url' => home_url( $new_page_slug ),
        'menu-item-status' => 'publish' ) );

That may not fix your problem. I couldn't test some things without knowing more about the theme settings.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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