在WooCommerce中,我使用的是this code from Remicorson,但它不起作用,我找不到问题所在。
这是我的代码:
// Display Fields
add_action('woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields');
// Save Fields
add_action('woocommerce_process_product_meta', 'woo_add_custom_general_fields_save');
function woo_add_custom_general_fields()
{
global $woocommerce, $post;
echo '<div class="options_group">';
// Custom fields will be created here...
woocommerce_wp_text_input(array(
'id' => '_number_field',
'label' => __('Environmental fee', 'woocommerce') ,
'placeholder' => '',
'description' => __('Enter the custom value here.', 'woocommerce') ,
'type' => 'number',
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
));
echo '</div>';
}
function woo_add_custom_general_fields_save($post_id)
{
// Number Field
$woocommerce_number_field = $_POST['_number_field'];
if (!empty($woocommerce_number_field)) update_post_meta($post_id, '_number_field', esc_attr($woocommerce_number_field));
}
function woo_add_cart_fee()
{
global $woocommerce;
$prod_fee = get_post_meta($item['product_id'], '_number_field', true);
// After that you need to add condition or do calculation in.
function add_custom_fees(WC_Cart $cart)
{
$fees = 0;
$prod_fee = get_post_meta($item['product_id'], '_number_field', true);
foreach($cart->get_cart() as $item) {
$fees+= $item['quantity'] * $prod_fee;
}
if ($fees != 0) {
$cart->add_fee('Handling fee', $fees);
}
}
$woocommerce->cart->add_fee('Handling', $fee, true, 'standard');
}
add_action('woocommerce_cart_calculate_fees', 'woo_add_cart_fee');
答案 0 :(得分:1)
您在后端产品页面中创建自定义字段并保存该自定义字段数据的代码正在运行。我只是为了在代码中添加一些解释而稍微个性化了一下:
null
您可以在管理产品页中找到此信息(使用自定义字段&#34;环境费&#34;):
问题来自您的
// Create and display Backend Product custom field add_action('woocommerce_product_options_general_product_data', 'ba_adding_custom_product_general_field'); function ba_adding_custom_product_general_field() { global $woocommerce, $post; echo '<div class="options_group">'; // Custom fields will be created here... woocommerce_wp_text_input(array( 'id' => '_number_field', 'label' => __('Environmental fee', 'woocommerce') , 'placeholder' => '', 'description' => __('Enter the custom value here.', 'woocommerce') , 'type' => 'number', 'custom_attributes' => array( 'step' => 'any', 'min' => '0' ) )); echo '</div>'; } // Save the submited data from Backend Product custom field add_action('woocommerce_process_product_meta', 'ba_saving_custom_product_general_field'); function ba_saving_custom_product_general_field($post_id) { // Get the submitted value $woocommerce_number_field = $_POST['_number_field']; // Create/Update the submitted value in postmeta table for this product if (!empty($woocommerce_number_field)) update_post_meta($post_id, '_number_field', esc_attr($woocommerce_number_field)); }
,因为您在该功能中嵌入了类似的功能,所以这不会明确起作用。
您可以在下面找到正确的工作代码,根据自定义字段计算添加购物车费用:
woo_add_cart_fee()