Snippets

Oscar García Arenas Bigfish - Minimum spend on the selected products

Created by Oscar García Arenas last modified
<?php
/**
 * Is a buy item?
 */
function bigfish_cart_item_match( $cart_item, $cart_rule, $rule ) {
	if ( WC_BOGOF_Cart::is_free_item( $cart_item ) || ! isset( $cart_item['data'] ) || ! is_callable( array( $cart_item['data'], 'get_id' ) ) || wc_bogof_cart_item_match_skip( $cart_rule, $cart_item ) ) {
		return false;
	}
	$match      = false;
	$product_id = $cart_item['data']->get_id();

	return $rule->is_buy_product( $product_id ) && ! $rule->is_exclude_product( $product_id );
}

/**
 * If the customer does not spend the minimum amount in the selected products, return zero free qty.
 */
function bigfish_free_item_quantity( $free_quantity, $cart_quantity, $rule, $cart_rule ) {
	$min_amount = $rule->get_meta( '_bigfish_minimumamount' );
	if ( ! empty( $free_quantity ) && ! empty( $min_amount ) ) {
		// check the spend in selected products.
		$subtotal = 0;
		$cart_contents = array_filter( WC()->cart->get_cart_contents() );
		foreach ( $cart_contents as $key => $cart_item ) {
			if ( bigfish_cart_item_match( $cart_item, $cart_rule, $rule ) ) {
				$subtotal += wc_bogof_get_cart_product_price( $cart_item['data'], array( 'qty' => $cart_item['quantity'] ) );
			}
		}
		if ( $subtotal <= floatval( $min_amount ) ) {
			$free_quantity = 0;
		}
	}
	
	return $free_quantity;
}
add_filter( 'wc_bogof_free_item_quantity', 'bigfish_free_item_quantity', 10, 4 );

/**
 * New tab "Custom fields".
 */
function bigfish_bogof_rule_data_tabs( $tabs ) {
	$tabs['custom_bigfish'] = array(
		'label'  => __( 'Custom fields', 'wc-buy-one-get-one-free' ),
		'target' => 'custom_bigfish_bogof_rule_data',
		'class'  => '',
	);
	return $tabs;
}
add_filter('wc_bogof_rule_data_tabs', 'bigfish_bogof_rule_data_tabs' );

/**
 * Output the field for handle the amount.
 */
function bigfish_bogof_rule_data_panels() {
	echo '<div id="custom_bigfish_bogof_rule_data" class="panel woocommerce_options_panel"><div class="options_group">';
	// minimum spend.
	woocommerce_wp_text_input(
		array(
			'id'          => '_bigfish_minimumamount',
			'label'       => __( 'Minimum spend on the selected products', 'wc-buy-one-get-one-free' ),
			'placeholder' => __( 'No minimum', 'wc-buy-one-get-one-free' ),
			'data_type'   => 'price',
			'desc_tip'    => true,
		)
	);
	echo '</div></div>';
}
add_action( 'wc_bogof_rule_data_panels', 'bigfish_bogof_rule_data_panels' );

/**
 * Save the custom field.
 */
function bigfish_bogof_admin_process_rule_object( $rule, $postdata ) {
	$value = isset( $postdata['_bigfish_minimumamount'] ) ? wc_format_decimal( $postdata['_bigfish_minimumamount'] ) : '';
	$rule->update_meta_data( '_bigfish_minimumamount', $value );
}
add_action( 'wc_bogof_admin_process_rule_object', 'bigfish_bogof_admin_process_rule_object', 10, 2 );

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.