0

I've two custom post types, type1 and type2

My current workflow of creating contents, from the user perspective

  • a user created posts of type1, i.e. post1, post2, post3 on a particular day
  • our system automatic create a post of type2 is at the end of the day, i.e. `post
  • the post_parent of post1, post2, post3 are set to post4

So, there are two cases:

  • How to auto reset the post_parent of post1, post2, post3 when post4 is deleted? (I want to retain post1, post2, post3)
  • How to auto delete post1, post2, post3 when post4 is deleted? (I want cleanup)
1

Hook in when a post is deleted, check for the post type, then manipulate post_parent of potential child posts (or delete the posts):

function wp_dev_174635_update_posts( $parent_id ) {

    $parent = get_post( $parent_id );
    if ( $parent->post_type !== 'type2' ) {
        return;
    }

    $posts = get_posts( array(
        'post_type'   => 'type1',
        'post_parent' => $parent_id,
    ) );
    foreach ( $posts as $post ) {
        // EITHER: Reset post parent entry
        wp_update_post( array(
            'ID'          => $post->ID,
            'post_parent' => 0,
        ) );

        // OR: Delete post
        // wp_delete_post( $post->ID );
    }
}

add_action( 'delete_post', 'wp_dev_174635_update_posts' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.