Hi,
I'm wondering what is the good way to delete child posts when parent post is deleted.
I have seen this topic :https://toolset.com/forums/topic/moving-child-posts-to-trash-upon-parent-is-sent-to-trash/
But, ok i know how i can get all child posts, but how i have to delete it ?
I don't want deleted with a bad way. First I have to deleted association ? and all elements in post meta with child id ? Maybe when i delete parent post association is deleted ? And i just need to delete childs ?
what is the good way to do that ?
Thanks for your answer.
Hi, if you want to permanently delete the posts and skip the trash, you can use wp_delete_post with the $force_delete parameter set to "true", and this will remove the post and all postmeta associated with the post. When you delete the child post, the post relationship association will automatically be deleted from the database.
https://codex.wordpress.org/Function_Reference/wp_delete_post
My issue is resolved now. Thank you!
I give my code, maybe it wiil be usefull for other projects.
add_action( 'wp_trash_post', 'wpv_delete_child_posts', 10 );
function wpv_delete_child_posts( $post_id ) {
// get child posts of this parent
$children = toolset_get_related_posts(
$post_id,
'programme-lot',
array(
'query_by_role' => 'parent',
'limit' => 999,
'return' => 'post_id',
'role_to_return' => 'child'
)
);
foreach ($children as $key => $child) {
if(empty($child))
{
return false;
}
wp_trash_post($child);
}
}