JRoy
4/27/2020 - 2:51 PM

Wordpress - Auto-Create child page on save

<?php

add_action( 'save_post', 'sm_check_for_thank_you_page', 10, 3 );
function sm_check_for_thank_you_page( $post_ID, $post, $update ) {
    // var_dump($post);
    // wp_die($post);
    if( 
        $update && 
        $post->post_type == 'page' && 
        $post->post_parent == 0 && 
        'trash' != get_post_status($post->ID) && 
        $post->page_template == 'templates/homepage.php'
    ) {
        $args = array(
            'post_parent' => $post->ID,
            'post_type' => 'page',
            'orderby' => 'menu_order'
        );
        $child_query = new WP_Query( $args );
        $found_children = false;
        if( $child_query->have_posts() ) {
            $found_children = true;
        }
        wp_reset_postdata();
        if( !$found_children ) {
            $page_id = wp_insert_post(add_magic_quotes(array(
                'post_title'     => 'Thank You',
                'post_name'      => 'thank-you',
                'post_content'   => '<h1>Thank You</h1>Thank you for reaching out to our team! One of our customer service team members will get back to you with pricing soon.',
                'post_status'    => 'publish',
                'post_author'    => 1,
                'post_type'      => 'page',
                'menu_order'     => 1,
                'comment_status' => 'closed',
                'ping_status'    => 'closed',
                'page_template' => 'templates/thank-you-template.php',
                'post_parent' => $post->ID
             )));
             set_transient("sm_added_thank_you_page", $page_id, 45);
            }
        }
    }

if ( get_transient( "sm_added_thank_you_page" ) ) {
    global $thank_you_transient;
    $thank_you_transient = get_transient( "sm_added_thank_you_page" ) ;
    function sample_admin_notice__success() {
        global $thank_you_transient;
        if ( $thank_you_transient ) { ?>
            <div class="notice notice-warning is-dismissible">
                <p><?php _e( 'A thank you page has been created for this landing page! <a href="' . get_edit_post_link($thank_you_transient) . '">View Here</a>', 'sample-text-domain' ); ?></p>
            </div>
            <?php
        }
    }
    add_action( 'admin_notices', 'sample_admin_notice__success' );
    delete_transient("sm_added_thank_you_page");
}