WPprodigy / woocommerce-product-fees

Add additional fees at checkout based on products that are in the cart.
https://wordpress.org/plugins/woocommerce-product-fees/
Other
26 stars 19 forks source link

Default product fee #47

Closed Jakob-Maudience closed 4 years ago

Jakob-Maudience commented 4 years ago

Is there a way we could set a default product fee in the settings to be applied if none exists on the product level?

WPprodigy commented 4 years ago

Hmm, probably not a great fit for this plugin, but could certainly be done with custom code. Something like this should do the trick:

/**
 * Add a default fee to cart if there is no product-level fee.
 * 
 * @param object $cart WC Cart object.
 * @return null
 */
add_action( 'woocommerce_cart_calculate_fees', function ( $cart ) {
    $default_fee = [
        'name'     => "My Fee Name", // Unique name for the fee. Multiple fees of the same name cannot be added.
        'amount'   => 10,            // Fee amount (do not enter negative amounts).
        'taxable'  => false,         // Is the fee taxable? (default: false).
        'tax_class' => '',           // The tax class for the fee if taxable. A blank string is standard tax class. (default: '').
    ];

    foreach( $cart->get_cart() as $item ) {
        $fee_data = [ get_post_meta( $item['id'], 'product-fee-name', true ), 'amount' => get_post_meta( $item['id'], 'product-fee-amount', true ) ];

        if ( 0 !== $item['variation_id'] && ( empty( $fee_data[0] ) || empty( $fee_data[1] ) ) ) {
            // Switch out for the parent's fee data.
            $fee_data = [ get_post_meta( $item['parent_id'], 'product-fee-name', true ), 'amount' => get_post_meta( $item['parent_id'], 'product-fee-amount', true ) ];
        }

        if ( empty( $fee_data[0] ) && empty( $fee_data[1] ) ) {
            // Add our default fee.
            $cart->add_fee( $default_fee['name'], $default_fee['amount'], $default_fee['taxable'], $default_fee['tax_class'] );
        }
    }
}, 20 );