I have a custom post type 'Departments' in Wordpress. When I create a page in this CPT, it automatically creates 3 subpages. That works fine!
But now I want two grandchildren pages to be created automatically and their parent must be Subpage2.
Right now I have it working like this:
Department1
-Subpage1
-Subpage2
-Subpage3
Department2
-Subpage1
-Subpage2
-Subpage3
-Subpage4
And I need it to be like this:
Department1
-Subpage1
-Subpage2
--GrandchildrenPage1 <--
--GrandchildrenPage2 <--
-Subpage3
Department2
-Subpage1
-Subpage2
--GrandchildrenPage1 <--
--GrandchildrenPage2 <--
-Subpage3
I currently have this code that works fine to create the 3 subpages:
// Add 3 Children CPT
function add_children_custom_post_type( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
$post_template = esc_html( get_page_template_slug( $post->ID ) );
if ( !wp_is_post_revision( $post_id ) && 'department' == get_post_type( $post_id ) && 'publish' == get_post_status( $post_id ) && $post_template === '') {
$show = get_post( $post_id );
if( 0 == $show->post_parent && $show->post_excerpt == "" ) {
$children =& get_children(
array(
'post_parent' => $post_id,
'post_type' => 'department',
'post_status' => array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash')
)
);
if( empty( $children ) ){
$posts = "";
$posts = ['Subpage1' => 'template-subpage1.php', 'Subpage2' => 'template-subpage2.php', 'Subpage3' => 'template-subpage3.php'];
$order = 1;
foreach ($posts as $title => $template) {
$child = array(
'post_type' => 'department',
'post_title' => $title,
'post_status' => 'draft',
'post_parent' => $post_id,
'post_author' => get_post_field('post_author', $post_id),
'menu_order' => $order,
'page_template' => $template
);
wp_insert_post( $child );
$order++;
}
}
}
}
}
add_action( 'save_post', 'add_children_custom_post_type' );