0

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 );
        }

    }
}
  • A better hook for what you're trying to do, is updated_postmeta. Just be careful or avoid infinite loop - i.e. "unhook" and "re-hook" where appropriate. – Sally CJ Mar 30 at 9:27
  • 1
    @SallyCJ thank you. I found the cause of the problem. I added as an answer. – Faruk Mar 30 at 9:36
0

I found the cause of the problem I was having. Since the post type I was working on was woccommerce orders (shop_order), I had to enter the post status correctly.

The edited code is as follows:

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 && 'shop_order' == $post->post_type) {

        $mettta = get_post_meta( $post->ID , "_post_color" , true );

        $args = array(
            'numberposts' => -1,
            'post_type' => 'shop_order',
            'post_parent' => $post->ID,
            'post_status' => array('wc-pending','wc-processing','wc-on-hold','wc-completed','wc-cancelled','wc-refunded','wc-failed','wc-shipping-progress')
        );
        $ChildIDs = get_posts( $args );

        foreach ($ChildIDs as $childID) {
            update_post_meta( $childID->ID, "_post_color", $mettta );
        }

    }
}
| improve this answer | |

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.