Question

To clarify, this question is merely on how to "save" or "update" a child post when the parent post is saved. Nothing more.

Hello to all of you brilliant and wonderful people. I need to auto-update all the child posts whenever the parent post is saved because I have a function that updates the categories to match the parent whenever the child post is updated. This should be pretty straightforward. The only catch is the child posts are a different post type than the parent, but they both share the same category taxonomy (child posts do not have unique categories). I'm thinking it can be done through 'save_post' function. Thanks in advance!!! Much much appreciated!!!

Was it helpful?

Solution

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;      
    }
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top