为什么我的 PHP 代码不允许我在 WooCommerce 中保存未选中的自定义复选框?

Why does my PHP Code not allow me to save an unchecked Custom Checkbox, in WooCommerce?

我正在开发一个具有 WooCommerce 功能的 WordPress 网站。

我创建了一个自定义复选框字段,它出现在 WooCommerce 产品仪表板中。为了创建复选框,我在 functions.php 文件中输入了以下代码:

function product_custom_fields_add(){

   global $post;

   $input_checkbox = get_post_meta( $post->ID, '_engrave_text_option', true );
   if( empty( $input_checkbox ) || $input_checkbox == 'no' ) $input_checkbox = '';

    echo '<div class="product_custom_field">';

    woocommerce_wp_checkbox(
        array(
            'id'        => '_engrave_text_option',
            'desc'      =>  __('set custom Engrave text field', 'woocommerce'),
            'label'     => __('Display custom Engrave text field', 'woocommerce'),
            'desc_tip'  => 'true',
            'value'     => $input_checkbox
        )
    );
    echo '</div>';
}
add_action('woocommerce_product_options_advanced', 'product_custom_fields_add');

为了保存输入的值,我在 functions.php 文件中输入了以下代码:

function woocommerce_product_custom_fields_save($post_id){
    if ( ! empty( $_POST['_engrave_text_option'] ) )
        update_post_meta($post_id, '_engrave_text_option', esc_attr( $_POST['_engrave_text_option'] ));
}
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');

复选框成功出现在产品仪表板中,并允许我成功 select 复选框并保存。当我然后去取消选中复选框时出现问题。出于某种原因,当我取消选中然后继续保存页面时,页面只是重新加载,复选框仍然处于选中状态。

有没有人能看出上面的代码有什么问题,可能是导致这个错误的原因?

它是 PHP 相关的东西,未选中的复选框不包含在 POST 数据中。 所以你需要有一些调整代码来保存部分:

  function woocommerce_product_custom_fields_save($post_id){               
            $_engrave_text_option = isset( $_POST['_engrave_text_option'] ) ? 'yes' : 'no';
            update_post_meta( $post_id, '_engrave_text_option', $_engrave_text_option );       
 }

add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');