How to auto-update child posts whenever the parent post is updated?

Hello again beautiful WP community. I managed to scrape together a solution in case anyone needs it. I’m sure it needs some cleaning up, but it works. The awesome thing is that it’s multi-purpose — just change the $args to hardcode any change to a tag, key, category, title, author, status, template or content in the child post whenever the parent post is updated.

What it doesn’t do: Unfortunately, one overzealous user who was unable to help erroneously downvoted this question as a duplicate (it’s not). This completely different function does not auto-update the child taxonomies to match the parent’s taxonomies when the parent post is saved (still looking for an answer to that), but in the meantime, you can pair the following function with the top section of code in this completely different question here in order to achieve that.

Keep making this place awesome!

add_action( 'save_post', 'update_children', 10, 2);
function update_children( $post_id, $post ) {

if ( 'trash' != $post->post_status ){

    // Is a top level post
    if( 0 === $post->post_parent ) {
        $children = array(
            'post_parent'   => $post->ID,
            'post_type'         => 'any',   //you can use also 'any'
            'fields'            => 'ids',   // Only Return IDs
            'post_status' => 'publish',
        );
        global $post;

        if ((is_array($children))&&(!empty( $children ))){
            $the_query = new WP_Query( $children );
        }
        // The Loop
        if ( $the_query->have_posts() ) :
        while ( $the_query->have_posts() ) : $the_query->the_post();
        $mypostids[] = get_the_ID();
        $updatethis = array (
                'fields'      => $mypostids,
                'post_status' => 'publish'
        );

        if ((is_array($children))&&(!empty( $children ))) {     
            foreach( $children as $child_ids ) {
                remove_action( 'save_post', 'update_children', 10, 2);
                wp_update_post( $updatethis );
                add_action( 'save_post', 'update_children', 10, 2);
            }           
        }
        endwhile;
        endif;      
    }
}
}

Leave a Comment