How can I restore posts from 'trash' with their previous post_status? - Wordpress
I have a Custom post type in wordpress in which when creating a new post 3 child subposts are created automatically. For example, I create the post and assign it some status 'Publish', 'pending', 'draft' or another:
Post Company 1
-Subpost 1 (it is created automatically)
-Subpost 2 (it is created automatically)
-Subpost 3 (it is created automatically)
Removing the parent (moves to 'trash' ) will also remove the subposts. But when you restore them, they should be in the state they were saved in before ('pending', 'draft', 'auto-draft' or something else).
How could I do that to restore the posts (parent and children) with their 'post-status' that they had defined before being moved to 'trash'?
This is my code that I am using to create the 3 child subposts automatically:
function add_children_custom_post_type( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) DOING_AUTOSAVE )
return;
if ( !wp_is_post_revision( $post_id ) 'companies' == get_post_type( $post_id ) 'publish' == 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' = 'companies'
)
);
if( empty( $children ) ){
//Children pages
$titles = ['Subpost1', 'Subpost2', 'Subpost3'];
foreach ($titles as $key=$title) {
$child = array(
'post_type' = 'companies',
'post_title' = $title,
'post_content' = '',
'post_status' = 'publish',
'post_parent' = $post_id,
'post_author' = get_post_field('post_author', $post_id),
'menu_order' = $key
);
wp_insert_post( $child );
}
}
}
}
}
add_action( 'save_post', 'add_children_custom_post_type' );
And this is the one I use to move the child posts of a parent post when the parent is deleted:
// Move to Trash
function trash_post_children($post_id) {
$parent_ID = $post_id;
$args = array(
'post_type' = 'companies',
'post_parent' = $parent_ID,
'posts_per_page' = -1,
'post_status' = array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash')
);
$children = get_posts($args);
if($children) {
foreach($children as $p){
wp_trash_post($p-ID, true);
}
}
}
add_action('trashed_post', 'trash_post_children');
And this other one is to restore the posts but they are always restored in 'draft' state:
// RestorePost
function restore_post_children($post_id) {
$parent_ID = $post_id;
$args = array(
'post_type' = 'companies',
'post_parent' = $parent_ID,
'posts_per_page' = -1,
'post_status' = 'trash'
);
$children = get_posts($args);
if($children) {
foreach($children as $p) {
wp_untrash_post($p-ID);
}
}
}
add_action('untrash_post', 'restore_post_children');
Topic post-status posts Wordpress
Category Web