将复选框添加到 WooCommerce 产品高级选项选项卡

Add checkbox to WooCommerce product advanced options tab

我正在尝试向 WooCommerce 中的产品页面添加一个复选框。它用于判断产品是否需要在结帐时签署的发布表。

这是在子主题中完成的。该复选框显示在我想要的产品的高级选项卡中,但未保存。

这是我的 functions.php 创建复选框并保存它的代码。

function add_release_checkbox() {
  $args = array(
    'label' => __('Release Form Required','woocommerce'), // Text in the editor label
    'value' => get_post_meta(get_the_id(), 'release_req', true), // meta_value where the id serves as meta_key
    'id' => 'release_req', // required, it's the meta_key for storing the value (is checked or not)
    'name' => __('Release Required','woocommerce'),
    'cbvalue' => true, // "value" attribute for the checkbox
    'desc_tip' => true, // true or false, show description directly or as tooltip
    'description' => __('Tells if a release form is required for this product.','woocommerce') // provide something useful here
  );
  woocommerce_wp_checkbox( $args );
}

add_action( 'woocommerce_product_options_advanced', 'add_release_checkbox' );

function save_release_meta($post_id) {
    write_log($_POST); // for debugging purposes write the post to the debug.log file
    $release = isset($_POST['release_req']) ? $_POST['release_req'] : '0';
    $product = wc_get_product($post_id);
    $product->update_meta_data('release_req', $release);
    $product->save();
}
add_action('woocommerce_process_product_meta', 'save_release_meta');

我把它做成一个文本框,它可以工作,所以问题是我做错了什么?即使我选中或取消选中它也不会保存。

这不起作用的原因是您在代码中使用了以下内容

'name' => __('Release Required','woocommerce'),

名称不一定是可翻译的,但应用方式有误


低于有效答案。我在哪里使用 woocommerce_admin_process_product_object 来保存而不是过时的 woocommerce_process_product_meta hook

function add_release_checkbox() {
    // Add checkbox
    $args = array(
        'label' => __( 'Release Form Required','woocommerce' ), // Text in the editor label
        'id' => 'release_req', // required, it's the meta_key for storing the value (is checked or not)
        'desc_tip' => true, // true or false, show description directly or as tooltip
        'description' => __('Tells if a release form is required for this product.','woocommerce') // provide something useful here
    );
    woocommerce_wp_checkbox( $args );
}

add_action( 'woocommerce_product_options_advanced', 'add_release_checkbox' );

// Save Field
function action_woocommerce_admin_process_product_object( $product ) {
    // Isset, yes or no
    $checkbox = isset( $_POST['release_req'] ) ? 'yes' : 'no';

    // Update meta
    $product->update_meta_data( 'release_req', $checkbox );
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );