我有一个关于WooCommerce购物车计数的问题。我想添加一个处理费用字段到每个产品,并显着计算总费用在购物车。根据我的研究,我在我的产品中创造了一个领域。Demo-1
下一步是在购物车中计算这个字段。我也在谷歌上搜索过这个问题,但我只能找到一些解决方案(Wordpress:在购物车中添加额外费用)来计算固定费用,而不是戏剧性的功能。Demo-2
// 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 ) );
}
add_action( 'woocommerce_cart_calculate_fees','endo_handling_fee' );
function endo_handling_fee() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$fee = 5.00;
$woocommerce->cart->add_fee( 'Handling', $fee, true, 'standard' );
}
如何修改函数来计算每个产品的费用,该值是我创建的自定义字段提供的,在小计列中?
现在,我正在尝试下面的代码。我认为关键是如何抓住产品的价值,让价值成为一个变量。
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');
function add_custom_fees( WC_Cart $cart ){
$fees = 0;
foreach( $cart->get_cart() as $item ){
$fees += $item[ 'quantity' ] * 0.08;
}
if( $fees != 0 ){
$cart->add_fee( 'Handling fee', $fees);
}
}
您需要的函数是get_post_meta,用于获取自定义字段的值。
$prod_fee = get_post_meta($item['product_id'] , '_number_field', true);
然后你可以把它累加起来,作为综合费用。
您需要从产品的元数据中获取产品费用,如@Anfelipe给出的代码
$prod_fee = get_post_meta($item['product_id'] , '_number_field', true);
之后,你需要添加条件或在。
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);
}
}