Auto add pages to primary menu with functions.php

Is it possible to have new pages automatically added to the primary menu via functions.php?

This particular theme will be deployed on a special version of multisite, so the checkbox which is available via admin isn’t an option.

Read More

I can’t seem to find anything in codex or on here.

Related posts

Leave a Reply

1 comment

  1. Not a specific answer, but will be too long for a comment. You could also try looking at the code that WordPress core uses itself. I know you said you couldn’t use the check box that auto-adds pages, but you could look over how it is being used. A little digging around (with a decent text editor you should be able to search for a phrase throughout the entire WordPress code base) in the WordPress code reveals:

    /**
     * Automatically add newly published page objects to menus with that as an option.
     *
     * @since 3.0.0
     * @access private
     *
     * @param string $new_status The new status of the post object.
     * @param string $old_status The old status of the post object.
     * @param object $post The post object being transitioned from one status to another.
     * @return void
     */
    function _wp_auto_add_pages_to_menu( $new_status, $old_status, $post ) {
        if ( 'publish' != $new_status || 'publish' == $old_status || 'page' != $post->post_type )
            return;
        if ( ! empty( $post->post_parent ) )
            return;
        $auto_add = get_option( 'nav_menu_options' );
        if ( empty( $auto_add ) || ! is_array( $auto_add ) || ! isset( $auto_add['auto_add'] ) )
            return;
        $auto_add = $auto_add['auto_add'];
        if ( empty( $auto_add ) || ! is_array( $auto_add ) )
            return;
    
        $args = array(
            'menu-item-object-id' => $post->ID,
            'menu-item-object' => $post->post_type,
            'menu-item-type' => 'post_type',
            'menu-item-status' => 'publish',
        );
    
        foreach ( $auto_add as $menu_id ) {
            $items = wp_get_nav_menu_items( $menu_id, array( 'post_status' => 'publish,draft' ) );
            if ( ! is_array( $items ) )
                continue;
            foreach ( $items as $item ) {
                if ( $post->ID == $item->object_id )
                    continue 2;
            }
            wp_update_nav_menu_item( $menu_id, 0, $args );
        }
    }
    

    This code is run on:

    add_action( 'transition_post_status',     '_wp_auto_add_pages_to_menu', 10, 3 );
    

    Maybe this will point you in the right direction and perhaps you can copy what WP is doing to do something similar.