Añadir cuota o descuento en el total del pedido en el checkout de WC

Añadir cuota o descuento en el total del pedido en el checkout de WC.

// Asignar descuento a cuota
add_action( "woocommerce_review_order_before_payment", "eb_refresh_checkout_on_payment_methods_change" );
function eb_add_checkout_fee_for_gateway() {

if ( is_admin() && ! defined( "DOING_AJAX" ) ) {
return;
}

$chosen_gateway = WC()->session->chosen_payment_method;

if ( $chosen_gateway == "bacs" ) {
global $woocommerce;
$percentage = -0.03;
$subtotal = $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total;
$total_sin_iva = $subtotal
$surcharge = $total_sin_iva * $percentage;
$woocommerce->cart->add_fee( "Descuento -3% (Transferencia bancaria)", $surcharge, true, "" );
}
}
add_action( "woocommerce_cart_calculate_fees", "eb_add_checkout_fee_for_gateway" );



// Recargar el checkout
add_action( "woocommerce_review_order_before_payment", "eb_refresh_checkout_on_payment_methods_change" );
function eb_refresh_checkout_on_payment_methods_change(){
?>
<script type="text/javascript">
(function($){
$( "form.checkout" ).on( "change", "input[name^="payment_method"]", function() {
$("body").trigger("update_checkout");
});
})(jQuery);
</script>
<?php
}
add_action( "woocommerce_review_order_before_payment", "eb_refresh_checkout_on_payment_methods_change" );

Ocultar código promocional del carrito y checkout

Quitar los códigos promocionales del carrito y checkout.

// hide coupon field on the cart page
function disable_coupon_field_on_cart( $enabled ) {
if ( is_cart() ) {
$enabled = false;
}
return $enabled;
}
add_filter( "woocommerce_coupons_enabled", "disable_coupon_field_on_cart" );


// hide coupon field on the checkout page
function disable_coupon_field_on_checkout( $enabled ) {
if ( is_checkout() ) {
$enabled = false;
}
return $enabled;
}
add_filter( "woocommerce_coupons_enabled", "disable_coupon_field_on_checkout" );

Filtrar JetSmartFilters añadiendo una categoría además de los filtros definidos

Filtrar JetSmartFilters añadiendo una categoría además de los filtros definidos.

function ebfilter_pre_get_posts( $query ) {
$ceb = $_SESSION["ceb"];
$term = get_term_by("slug", get_query_var("s"), "product_tag");
$tax_query = array(
"taxonomy" => "product_cat",
"terms" => array ( $ceb ),
"field" => "term_id",
"operator" => "IN",
);
$query->tax_query->queries[] = $tax_query;
$query->query_vars["tax_query"] = $query->tax_query->queries;
$query->set("tax_query", $query->tax_query->queries);
}



function ebfilter_products_shortcode_args( $args, $atts, $type ){
//echo "<pre>";print_r ($type);echo "</pre>";
if ( wp_doing_ajax() && $type === "products" ) {
add_action( "pre_get_posts", "ebfilter_pre_get_posts", 1 );
}
else {
remove_action( "pre_get_posts", "ebfilter_pre_get_posts", 1 );
}

return $args;
//echo "<pre>";print_r ($atts);echo "</pre>";
}

add_filter( "woocommerce_shortcode_products_query", "ebfilter_products_shortcode_args", 10, 3 );

Modificar precio y/o su presentación HTML del precio de productos

Modificar precio y/o su presentación HTML del precio de productos.

function set_eb_price_html ( $price, $product ){

if ( is_admin() && ! wp_doing_ajax() ) {
return $price;
}


if ( is_cart() || is_checkout() ) {
return $price;
}

if ($product->is_type("simple")) {
$envio_pen = floatval(get_post_meta( $product->get_id(), "_ebshipping_peninsula", true ));
$envio_bal = floatval(get_post_meta( $product->get_id(), "_ebshipping_baleares", true ));

$ebshipping_options = $_COOKIE["ebshipping_options"];

if ( $ebshipping_options === "_ebshipping_baleares" ) {
$text_envio = "<br><span style="font-size:11px;color: #9e9e9e;">Envío Baleares incluido</span>" ;

}
else {
$text_envio = "<br><span style="font-size:11px;color: #9e9e9e;">Envío Península incluido</span>" ;
}

$price = sum_envio_price (floatval($product->get_price()), $envio_pen, $envio_bal, $tax, 0 );
$sin_iva = sum_envio_price (floatval($product->get_price()), $envio_pen, $envio_bal, 0, 0 );
$iva = wc_price ( $price - $sin_iva ) ;
return wc_price( round ($price, 0)) . $text_envio . "<br><span style="font-size:12px;color: #82a398; line-height:16px;">Incluye IVA</span>";
}
else {
return $price;
}
}

add_filter( "woocommerce_get_price_html", "set_eb_price_html", 100, 2 );

Pasar campos personalizados de producto al carrito de compra y al pedido en WC

Pasar campos personalizados de producto al carrito de compra y al pedido en Woocommerce.

/**
* Add engraving text to cart item.
*
* @param array $cart_item_data
* @param int $product_id
* @param int $variation_id
*
* @return array
*/
function add_ebshipping_to_cart_item( $cart_item_data, $product_id, $variation_id ) {

$pen = get_post_meta( $product_id, "_ebshipping_peninsula", true );
$bal = get_post_meta( $product_id, "_ebshipping_baleares", true );

$cart_item_data["pen"] = $pen;
$cart_item_data["bal"] = $bal;

return $cart_item_data;
}
add_filter( "woocommerce_add_cart_item_data", "add_ebshipping_to_cart_item", 10, 3 );




/**
* Display engraving text in the cart.
*
* @param array $item_data
* @param array $cart_item
*
* @return array
*/
function display_ebshipping_text_cart( $item_data, $cart_item ) {
if ( empty( $cart_item["pen"] ) ) {
return $item_data;
}

$item_data[] = array(
"key" => __( "ebshipping", "pen" ),
"value" => wc_clean( $cart_item["pen"] ),
"display" => "",
);

if ( empty( $cart_item["bal"] ) ) {
return $item_data;
}

$item_data[] = array(
"key" => __( "ebshipping", "bal" ),
"value" => wc_clean( $cart_item["bal"] ),
"display" => "",
);

return $item_data;
}
//add_filter( "woocommerce_get_item_data", "display_ebshipping_text_cart", 10, 2 );




/**
* Add engraving text to order.
*
* @param WC_Order_Item_Product $item
* @param string $cart_item_key
* @param array $values
* @param WC_Order $order
*/
function add_ebshipping_to_order_items( $item, $cart_item_key, $values, $order ) {
if ( empty( $values["pen"] ) && empty( $values["bal"] )) {
return;
}

$item->add_meta_data( __( "ebshipping_pen", "pen" ), $values["pen"] );
$item->add_meta_data( __( "ebshipping_bal", "bal" ), $values["bal"] );
}
add_action( "woocommerce_checkout_create_order_line_item", "add_ebshipping_to_order_items", 10, 4 );




function checkout_update_refresh_shipping_methods( $post_data ) {
$packages = WC()->cart->get_shipping_packages();
foreach ($packages as $package_key => $package ) {
WC()->session->set( "shipping_for_package_" . $package_key, true ); // Or true
}
WC()->cart->calculate_shipping();
$packages = WC()->shipping->get_packages();

WC()->cart->calculate_totals();
}

add_action("woocommerce_checkout_update_order_review", "checkout_update_refresh_shipping_methods", 10, 1);

Añadir o quitar provincias de los formularios checkout en WC

Añadir o quitar provincias de los formularios checkout en WC.

/**
* Añadir o quitar provincias a los formularios del checkout
*/

function custom_woocommerce_states( $states ) {

global $woocommerce ;
if ( ! is_checkout() ) {
return $states;
}
//echo "<pre>"; print_r ($states["ES"] ); echo "</pre>";
$ebshipping_options = $_COOKIE["ebshipping_options"];

if ( $ebshipping_options == "_ebshipping_baleares" ) {
// Solo Baleares
$states["ES"] = array(
"PM" => "Baleares",
);
}
else {
// Península excepto Baleares, Ceuta, Melilla y Tenerife
if ( isset ( $states["ES"]["PM"] ) ) {
unset( $states["ES"]["PM"]);
}

if ( isset ( $states["ES"]["CE"] ) ) {
unset( $states["ES"]["CE"]);
}

if ( isset ( $states["ES"]["ML"] ) ) {
unset( $states["ES"]["ML"]);
}

if ( isset ( $states["ES"]["GC"] ) ) {
unset( $states["ES"]["GC"]);
}

if ( isset ( $states["ES"]["TF"] ) ) {
unset( $states["ES"]["TF"]);
}
}

//echo "<pre>"; print_r ($states ); echo "</pre>";
return $states;
}

add_filter( "woocommerce_states", "custom_woocommerce_states" );

Forzar calculo de gasto de envío al añadir producto al carrito de compras WC

Forzar calculo de gasto de envío al añadir producto al carrito de compras WC.

function woocommerce_custom_price_to_cart_item( $cart_object ) {  
//if( !WC()->session->__isset( "reload_checkout" )) {

// Mandatory to make it work with shipping methods
foreach ( WC()->cart->get_shipping_packages() as $package_key => $package ){
WC()->session->set( "shipping_for_package_" . $package_key, true );
}
WC()->cart->calculate_shipping();
//}
}
add_action( "woocommerce_before_calculate_totals", "woocommerce_custom_price_to_cart_item", 99 );

Añadir pestaña y campos personalizados a datos de productos WC

Crear una pestaña a la ficha de productos de Woocommerce, para incluir campos personalizados del producto.

/**
* Crea la pestaña
*/
function custom_product_tabs( $tabs) {
$tabs["ebshipping"] = array(
"label" => __( "EB Shipping", "woocommerce" ),
"target" => "ebshipping_options",
);
return $tabs;
}
add_filter( "woocommerce_product_data_tabs", "custom_product_tabs" );




/**
* Campos de la pestaña
*/
function ebshipping_options_product_tab_content() {
global $post;

// Note the "id" attribute needs to match the "target" parameter set above
?><div id="ebshipping_options" class="panel woocommerce_options_panel"><?php
?><div class="options_group"><?php
woocommerce_wp_text_input( array(
"id" => "_ebshipping_peninsula",
"label" => __( "Península", "woocommerce" ),
"desc_tip" => "true",
"description" => __( "Costo de envío para península", "woocommerce" ),
) );
woocommerce_wp_text_input( array(
"id" => "_ebshipping_baleares",
"label" => __( "Baleares", "woocommerce" ),
"desc_tip" => "true",
"description" => __( "Costo de envío para baleares", "woocommerce" ),
) );
?></div>

</div><?php
}
add_filter( "woocommerce_product_data_panels", "ebshipping_options_product_tab_content" ); // WC 2.6 and up



/**
* Guarda los campos
*/
function save_ebshipping_option_fields( $post_id ) {

if ( isset( $_POST["_ebshipping_peninsula"] ) ) :
update_post_meta( $post_id, "_ebshipping_peninsula", floatval( $_POST["_ebshipping_peninsula"] ) );
endif;

if ( isset( $_POST["_ebshipping_baleares"] ) ) :
update_post_meta( $post_id, "_ebshipping_baleares", floatval( $_POST["_ebshipping_baleares"] ) );
endif;
}
add_action( "woocommerce_process_product_meta_simple", "save_ebshipping_option_fields" );
add_action( "woocommerce_process_product_meta_variable", "save_ebshipping_option_fields" );

Woocommerce: No reducir stocks en pedidos con pago Transferencia bancaria

Muchos pedidos con forma de pago “transferencia bancaria” nunca se recibe la transferencia.

Las funciones siguientes hacen que el stocks no se reduzca automáticamente en los pedidos con el método de pago “transferencia bancaria”, en cambio si se actualiza el stock cuando el pedido cambia de estatus de “en espera” a “en proceso” o “completado”.

// NO ACTUALIZAR STOCKS EN PEDIDOS POR TRANSFERENCIA BANCARIA 
function wcs_do_not_reduce_onhold_stock( $reduce_stock, $order ) {
    if ( $order->has_status( 'on-hold' ) && $order->get_payment_method() == 'bacs' ) {
        $reduce_stock = false;
    }
    return $reduce_stock;
}
add_filter( 'woocommerce_can_reduce_order_stock', 'wcs_do_not_reduce_onhold_stock', 10, 2 );


// ACTUALIZAR STOCKS EN PEDIDOS POR TRANSFERENCIA BANCARIA CUANDO ESTADO PASA A COMPLETADO
function order_stock_reduction_based_on_status( $order_id, $old_status, $new_status, $order ){
    // Only for 'processing' and 'completed' order statuses change
    if ( $new_status == 'processing' || $new_status == 'completed' ) {
    $stock_reduced = get_post_meta( $order_id, '_order_stock_reduced', true );
        if( empty($stock_reduced) && $order->get_payment_method() == 'bacs' ){
            wc_reduce_stock_levels($order_id);
        }
    }
}
add_action( 'woocommerce_order_status_changed', 'order_stock_reduction_based_on_status', 20, 4 );