如何根据条件自动更新 acf 字段?

How to auto update an acf field based on the condition?

我有两个带有 acf 字段的自定义 post 类型。
自定义 Post_A,其中有 2 个字段 - 标题/已提交
自定义 Post_B,它有 2 个字段 - 标题/百分比
Post_A 和 B 有相同的标题(即登录用户名)并且它们已经存在。

当“已提交”字段在 Post_A 中的值为“完成”时,我需要在 Post_B 中自动更新值为“50”的“百分比”字段。
我尝试了以下代码,但它没有将“50”更新为 Post_B。
你能更正我的代码吗?

$posts = get_posts(array(
    'author'            => get_current_user_id(),
    'posts_per_page'    => -1,
    'post_type'         => 'post_a',
    'meta_key'          => 'submitted',
    'meta_value'        => 'done'
));

$the_query = new WP_Query( $posts );
$the_count = count($the_query); 

if($the_count>0) {
foreach ($the_query as $is_done){
$my_post = array();
$my_post['post_type'] = 'post_b';
$my_post['post_title'] = the_title();

// Update the post into the database
$field_key = "field_606cb546456343";
$value = "50";
update_field( $field_key, $value);
}
}

谢谢。

您可以使用将在特定 post 类型上触发的 save_post_{$post->post_type} 操作挂钩。检查下面的代码。

function update_post_b( $post_id, $post, $update ){

    $post_a_title = get_the_title( $post_id );

    $posts = array(
        'author'            => get_current_user_id(),
        'posts_per_page'    => -1,
        'post_type'         => 'post_b'
    );

    $post_b = new WP_Query( $posts );

    if( $post_b->have_posts() ){ while ( $post_b->have_posts() ) { $post_b->the_post();
        if( $post_a_title == get_the_title() ){
            update_post_meta( get_the_ID(), 'percent', 50 );    
        }
    } }

}
add_action( 'save_post_post_a', 'update_post_b', 10, 3 );

有用的链接