Quiero agregar un valor porcentual a los precios de los artículos del carrito en función de la pasarela de pago seleccionada.
El problema al que me enfrento es que el precio del producto de variación no se actualiza para el precio del producto. El precio seleccionado inicialmente se muestra todo el tiempo.
¿Cómo puedo obtener el precio modificado en consecuencia?
Mi código hasta ahora:
// Set custom cart item price function add_custom_price( $cart ) { // This is necessary for WC 3.0+ if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; // Avoiding hook repetition (when using price calculations for example | optional) if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return; // Loop through cart items foreach ( $cart->get_cart() as $cart_item ) { $chosen_payment_method = WC()->session->get('chosen_payment_method'); if($chosen_payment_method == 'cod') { $increaseby = 3; } elseif($chosen_payment_method == 'paypal') { $increaseby = 8; } else { $increaseby = 10; } $price = get_post_meta($cart_item['product_id'] , '_price', true); $price = $price + (($price * $increaseby)/100); $cart_item['data']->set_price( $price ); } } add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);Cualquier ayuda muy apreciada.
Hay algunos errores en tu código.
WC()->session->get( 'chosen_payment_method' ); fuera del bucle foreachget_post_meta() no es necesario para obtener el precio, puede usar get_price()Entonces obtienes:
function action_woocommerce_before_calculate_totals( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return; // Get payment method $chosen_payment_method = WC()->session->get( 'chosen_payment_method' ); // Compare if ( $chosen_payment_method == 'cod' ) { $increaseby = 3; } elseif ( $chosen_payment_method == 'paypal' ) { $increaseby = 8; } else { $increaseby = 10; } // Loop through cart items foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) { // Get price $price = $cart_item['data']->get_price(); // Set price $cart_item['data']->set_price( $price + ( $price * $increaseby ) / 100 ); } } add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 ); function action_wp_footer() { if ( is_checkout() && ! is_wc_endpoint_url() ) : ?> <script type="text/javascript"> jQuery(function($){ $( 'form.checkout' ).on( 'change', 'input[name="payment_method"]', function() { $(document.body).trigger( 'update_checkout' ); }); }); </script> <?php endif; } add_action( 'wp_footer', 'action_wp_footer' );