减少 WPForm 提交上的 WordPress 自定义字段

问题描述 投票:0回答:1

我的网站有一个问题,我在其中创建了 CPT,称为“活动”,我在其中填充了 ACF,在其中创建了活动名称、日期、艺术家、描述和人数,在其中输入了可以参加活动的人数(某些内容)例如该活动的注册)。现在,我为我的活动创建了 Elementor 单帖子页面,我在其中放置了用于注册的 WPForm。现在,我希望每次注册都能减少可用门票的数量。

add_action('wpforms_process_complete', 'reduce_custom_field_on_form_submission', 10, 4);
function reduce_custom_field_on_form_submission($form_id, $entry_id, $form_data, $entry_data) {
    if ($form_id == 56797) {
        $post_id = $entry_data['post_id'];
        $custom_field_name = 'number_of_people';
        $amount_to_reduce = 1;

        $current_value = get_field($custom_field_name, $post_id);

        if ($current_value !== false) {
            $new_value = max(0, $current_value - $amount_to_reduce);
            
            update_field($custom_field_name, $new_value, $post_id);
        }
    }
}
wordpress advanced-custom-fields custom-post-type acfpro
1个回答
0
投票

看来您使用的钩子

wpforms_process_complete
不正确。在 https://wpforms.com/developers/wpforms_process_complete/ 上查看他们的文档,它引用了其功能的示例。我不使用 WP Forms,所以我无法对此进行测试,但请检查您所在字段的表单字段 ID,并替换我评论的位置。 [6] 是要替换的数字。

add_action( 'wpforms_process_complete', 'reduce_custom_field_on_form_submission', 10, 4 );
function reduce_custom_field_on_form_submission( array $fields, array $entry, array $form_data, int $entry_id ) {
    if ( 56797 === absint( $form_data['id'] ) ) {
        // Get the full entry object.
        $entry = wpforms()->entry->get( $entry_id );

        // Fields are in JSON, so we decode to an array.
        $entry_fields = json_decode( $entry->fields, true );
        // Entry Fields are done by field ID from the form builder. Replace [6] with whatever your field's number is.
        $post_id = $entry_fields[6]['value'];

        $current_value = get_field( 'number_of_people', $post_id );

        if ( false !== $current_value ) {
            $new_value = max( 0, $current_value - 1 );

            update_field( 'number_of_people', $new_value, $post_id );
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.