Automatically create child pages when saving a (parent) page

I have a bit of a tricky one…

I have a hierarchical Custom Post Type (‘shows’) that represents events. Is it possible for the user to create a new page (ie show), save the page and for WordPress to automatically create a defined set of child pages with defined names?

Ideally each child page would have a specific Custom Taxonomy applied to it automatically as it is created.

The icing on the cake would be if those child pages were saved as drafts and not published at that point.

Note that the number of child pages, their names and the taxonomy applied can be hard coded and won’t change.

Here is what I need:

//Save parent page
London 2013

//Children automatically created
London 2013
    -About (taxonomy: about)
    -Visitor Info (taxonomy: info)
    -Exhibitors (taxonomy: exhibitors)
    -Sponsors (taxonomy: sponsors)
    -Press (taxonomy: press)

1
1

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