如果单击WooCommerce中的复选框,则显示自定义产品字段

时间:2019-03-26 09:12:03

标签: wordpress woocommerce custom-fields

我有一个代码,可在产品编辑页面上显示该复选框。

这是我的代码:

// Display Roast Level Custom Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_roast_general_fields' );

function woo_roast_general_fields() {
// Create a custom checkbox field

// Checkbox
woocommerce_wp_checkbox( 
array( 
  'id' => '_roast', 
  'label' => __('Roast Level', 'woocommerce' ), 
  'description' => __( 'Enable roast level!', 'woocommerce' ) 
)
); 

}

// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_roast_general_fields_save' );

/** Hook callback function to save custom fields information */
function woo_roast_general_fields_save( $post_id ) {

// Save Checkbox
$checkbox = isset( $_POST['_roast'] ) ? 'yes' : 'no';
update_post_meta( $post_id, '_roast', $checkbox );
}

单击此复选框时,在单个产品的页面上,应显示选择字段。选择选项后,这些数据应显示在购物车中,结帐页面,“谢谢”页面,电子邮件以及编辑订单时。

这是我的第二个代码:

// The product custom field before add-to-cart button 
add_action( 'woocommerce_before_add_to_cart_button', 'woo_roast_custom_field' );

function woo_roast_custom_field() {
global $product;

echo '<div>';

woocommerce_form_field( 'roast_custom_field', array(
    'type'          => 'select',
    'class'         => array('my-field-class form-row-wide'),
    'label'         => __('Roast Level'),        
    'required'      => false,
    'options'   => array( 
        ''      => 'Please select', 
        'Blue'  => 'Blue', 
        'Rare'  => 'Rare',
        'Medium Rare'   => 'Medium Rare',
        'Medium'    => 'Medium',
        'Medium Well'   => 'Medium Well',
        'Well Done' => 'Well Done'
)), '' );

echo '</div>';
}

// Save the new unique value in the array of values (as product meta data)
add_action( 'woocommerce_add_to_cart', 'roast_custom_field_add_to_cart', 20, 6 );

function roast_custom_field_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){

if( isset($_POST['roast_custom_field']) ){
    // Get the array of existing values
    $roast_values   = (array) get_post_meta( $product_id, '_roast_custom_field_values', true );
    // append the new value to the array of values
    $roast_values[] = sanitize_text_field( $_POST['roast_custom_field'] );
    // Save the appended array
    update_post_meta( $product_id, '_roast_custom_field_values', $roast_values );
}

}

但是不幸的是,我不知道如何创建条件,以便当您单击复选框时,单个产品页面上会出现一个选择框。

应注意,如果未激活该复选框,则不应在单个产品的页面上显示选择字段。

另外,我不太确定保存数据时代码的正确性。

我请求您的帮助!

0 个答案:

没有答案