WordPress高级自定义字段:有关自定义帖子删除的更新字段

时间:2019-01-21 22:38:56

标签: php wordpress advanced-custom-fields

我要在删除自定义帖子类型(CPT)时更新一个字段。现在,我有一个关系字段 trainees 作为培训课程字段组的一部分。 受训者字段填充受训者CPT中的值。

每当更新培训课程时,我都会用以下代码计算培训地点:

function my_acf_save_post( $post_id ) {

// get new value
$number_of_places_available = get_field('number_of_places_available');
$number_of_trainees = count(get_field('trainees')); 
if ( empty(get_field('trainees')) ) {
  $number_of_places_left = $number_of_places_available;
} else {
  $number_of_places_left = $number_of_places_available - $number_of_trainees;
}


// do something
update_field('number_of_places_left', $number_of_places_left, $post_id);
}

add_action('acf/save_post', 'my_acf_save_post', 20);  

剩余的培训课程是后端中的一个只读字段,可以计算出来。

我要做的是更新实际删除受训者(移至废纸))后剩余的培训位置。当前,当我删除受训者时,我必须保存该培训课程,该受训者所属的其余培训位置才能正确更新。我想在实际删除受训者而无需保存培训课程的情况下更新此字段。

我正在尝试使用岗位状态转换来做到这一点,但这似乎不起作用,这意味着当我在后端刷新培训课程时,即使受训者已从关系字段中删除,可用位置的数量尚未更新,只有在保存培训课程时才会更新:

function on_publish_trash_post( $post ) {
    if ($post->post_type != 'trainee'){
        return;
    }

// get new value
$number_of_places_available = get_field('number_of_places_available');
$number_of_trainees = count(get_field('trainees'));
if ( empty(get_field('trainees')) ) {
  $number_of_places_left = $number_of_places_available;
} else {
  $number_of_places_left = $number_of_places_available - $number_of_trainees;
}

// do something
update_field('number_of_places_left', $number_of_places_left, $post->ID);
}

add_action(  'publish_to_trash',  'on_publish_trash_post', 10, 1 );

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

为感兴趣的人找到了解决方案:

function gm_trash_trainee( $post_id ) {
    $post_type = get_post_type( $post_id );
    $post_status = get_post_status( $post_id );
    if ( $post_type == 'trainee' ) {

        $args = array( 'post_type' => 'training_course');

        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post();
            $number_of_places_available = get_field('number_of_places_available', the_ID());
            $number_of_trainees = count(get_field('trainees', the_ID()));
            $number_of_places_left = $number_of_places_available - $number_of_trainees;
            update_field('number_of_places_left', $number_of_places_left, the_ID());

        endwhile;
    }
}
add_action( 'trashed_post', 'gm_trash_trainee' );