How to update/add child posts meta whenever the parent post meta is updated?
I couldn’t find a solution to a very simple problem.
When a meta value for the parent post is updated, I want the meta value of all child posts linked to this parent post to be updated.
For example: I want the “red” meta value to be automatically selected for the child posts when the “red” meta value is selected for the parent post. (for the _post_color meta key) Or if this parent post value updated, value must change automatically in child posts too.
I tried to do it using the code below, but it did not help. I added it to functions.php file.
add_action('save_post', 'change_child_posts_meta', 10, 2);
add_action('post_updated', 'change_child_posts_meta', 10, 2);
function change_child_posts_meta($post_id, $post)
{
if ( $post->post_parent == 0 && 'my_post_type' == $post->post_type) {
$mettta = get_post_meta( $post->ID , "_post_color" , true );
$args = array(
'post_parent' => $post->ID,
'fields' => 'ids',
);
$ChildIDs = get_children($args);
foreach ($ChildIDs as $childID) {
update_post_meta( $childID, "_post_color", $mettta );
}
}
}
Leave an answer