-1

Here is the process I like to achieve: 1. There's a checkbox on product page, user can decide to add custom service beside the product or not 2. If user checks the box, it adds a custom fee to the cart, but it's based on the product quantity e.g.: if a user adds 2 of the same product to the cart, and the checkbox is checked, it automatically adds 2x custom fee to the cart.

Could anyone help me with this? (I try to use as few plugins an I can, so try to achieve this via php snippet)

Here is my code (it adds the custom fee one times):

<?php
function transfer_fee() {
    if ( has_term( 'transfer', 'product_cat' ) ) {
        echo '<label><input type="checkbox" name="transfer" value="No">Add transfer (1 USD / person)</label>';
    } elseif {
        echo 'No transfer';
    }
}
add_action( 'woocommerce_before_add_to_cart_quantity', 'transfer_fee' );

function store_transfer_fee( $cart_item, $product_id ) {
    if( isset( $_POST['transfer'] ) ) $cart_item['transfer'] = $_POST['transfer'];
     return $cart_item;
}
add_filter( 'woocommerce_add_cart_item_data', 'store_transfer_fee', 10, 2 );

function add_checkout_transfer_fee() {
     foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
                if ( isset( $cart_item['transfer'] ) ) {
                        $itsagift = true;
                        break;
                }
        }
        if ( $itsagift == true ) WC()->cart->add_fee( 'Transfer', 1 );
}
add_action( 'woocommerce_cart_calculate_fees', 'add_checkout_transfer_fee' );
?>
Nadam
  • 39
  • 1
  • 6

1 Answers1

0

Assuming you mean this?

// Add checkbox before add to cart quantity
function transfer_fee() {
    if ( has_term( 'transfer', 'product_cat' ) ) {
        echo '<label><input type="checkbox" name="transfer" value="No">Add transfer (1 USD / person)</label>';
    } else {
        echo 'No transfer';
    }
}
add_action( 'woocommerce_before_add_to_cart_quantity', 'transfer_fee' );

// Add the cart meta data.
function store_transfer_fee( $cart_item_data, $product_id, $variation_id ) {
    if( isset( $_POST['transfer'] ) ) {
        $cart_item_data['transfer'] = $_POST['transfer'];
    }
    return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'store_transfer_fee', 10, 3 );

// Calculate fees
function add_checkout_transfer_fee( $cart_object ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        if ( isset( $cart_item['transfer'] ) ) {
            $itsagift = true;

            // Get quantity
            $quantity = $cart_item['quantity'];

            break;
        }
    }

    // Set fee
    $fee = 1;

    // True
    if ( $itsagift ) {
        WC()->cart->add_fee( 'Transfer', $fee * $quantity );
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'add_checkout_transfer_fee', 10, 1 );
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50