Automatically create child pages when saving a (parent) page

Use the save_post action to run some code when a new show is created, then use wp_insert_post to create your child pages.

Here’s an example to get you started – First, filter out any saves that are auto-saves, post revisions, auto-drafts, and other post types. Once you know it’s your show type, you can check if it has a parent to filter out saves of your child pages. Then check if the page already has children, if not, set up your post data and insert the child pages.

function wpa8582_add_show_children( $post_id ) {  
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return;

    if ( !wp_is_post_revision( $post_id )
    && 'show' == get_post_type( $post_id )
    && 'auto-draft' != get_post_status( $post_id ) ) {  
        $show = get_post( $post_id );
        if( 0 == $show->post_parent ){
            $children =& get_children(
                array(
                    'post_parent' => $post_id,
                    'post_type' => 'show'
                )
            );
            if( empty( $children ) ){
                $child = array(
                    'post_type' => 'show',
                    'post_title' => 'About',
                    'post_content' => '',
                    'post_status' => 'draft',
                    'post_parent' => $post_id,
                    'post_author' => 1,
                    'tax_input' => array( 'your_tax_name' => array( 'term' ) )
                );
                wp_insert_post( $child );
            }
        }
    }
}
add_action( 'save_post', 'wpa8582_add_show_children' );

Leave a Comment