Agregar precios adicionales a cada producto de Woocomerce



add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' );
function fabric_length_product_field() {
global $product;

if( $product->is_type('variable') ) return; // Not variable products

$domain = 'woocommerce';
$text = array(
__('cards', $domain),
__('card', $domain),
__('Total', $domain),
get_woocommerce_currency_symbol(),
);

// Select Options array
$options = array(
"" => __('Seleccionar...'),
"15.00" => "Lima Metropolitana - 15.00",
"20.00" => "Callao - 20.00",
"25.00" => "Provincia - 25.00"
);

// Select field
woocommerce_form_field('cards_pack', array(
'type' => 'select',
'class' => array('my-field-class form-row-wide'),
'label' => __('Escoger destino', $domain),
'required' => true,
'options' => $options,
),'');

// Data to be transmitted to jQuery
$base_price = (float) wc_get_price_to_display( $product );
$prices = array(
'' => wc_price($base_price),
'12.00' => wc_price($base_price + 12),
'15.00' => wc_price($base_price + 15),
'20.00' => wc_price($base_price + 20),
'25.00' => wc_price($base_price + 25),
)

// jQuery code
?>

get_price();

// New price calculation
$new_price = $base_price + $pack_price;

// Prepare and save the data array
$cart_item_data['pack_data'] = array(
'cards' => (int) $cards,
'pack' => (int) $pack_price,
'new_price' => (float) $new_price,
);
$cart_item_data['unique_key'] = md5( microtime() . rand() ); // Make each item unique

return $cart_item_data;
}

// Set conditionally a custom item price
add_action('woocommerce_before_calculate_totals', 'set_cutom_cart_item_price', 20, 1);
function set_cutom_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;

if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;

foreach ( $cart->get_cart() as $cart_item ) {
if ( isset( $cart_item['pack_data']['new_price'] ) )
$cart_item['data']->set_price( $cart_item['pack_data']['new_price'] );
}
}


// Display custom data in checkout page
add_filter( 'woocommerce_get_item_data', 'display_custom_cart_item_data', 10, 2 );
function display_custom_cart_item_data( $cart_data, $cart_item ) {
$domain = 'woocommerce';

if ( isset( $cart_item['pack_data']['new_price'] ) ){
$cart_data[] = array('name' => __( 'Cards pack', $domain ),
'value' => $cart_item['pack_data']['cards'] );
}
return $cart_data;
}

Deja un comentario