Minimum Order Quantity | Custom field

Hi there, I was wondering how to come up with a code snippet that forces the client to select a minimum amount of a listintg article and following your docs I managed to write this, however is not working.

Is there any mistake in the syntax or functions calling?
Is it possible to have a optional custom field similar to the one existing but establishing a minimum instead of a maximum?

Code:

<?php
// Agregar campo de cantidad mínima a productos de Hivepress
function hivepress_agregar_campo_minimo() {Preformatted text
   hivepress()->product->add_field(
      array(
         'id' => '_minimo',
         'label' => __('Cantidad Mínima', 'hivepress'),
         'type' => 'number',
         'step' => 1,
         'min' => 1
      )
   );
}
add_action('hivepress_product_price', 'hivepress_agregar_campo_minimo');

// Validar cantidad mínima antes de agregar producto al carrito
function hivepress_validar_cantidad_minima($passed, $product_id, $quantity) {
   $minimo = get_post_meta($product_id, '_minimo', true);
   if ($quantity < $minimo) {
      wc_add_notice(__('La cantidad mínima para este producto es de '.$minimo.' unidades.', 'woocommerce'), 'error');
      $passed = false;
   }
   return $passed;
}
add_filter('woocommerce_add_to_cart_validation', 'hivepress_validar_cantidad_minima', 10, 3);
?>

Thanks in advance,
Eduardo

Thank you for waiting. If you mean to change the minimum quantity field in the listing buy form on the single listing page, then please try this PHP snippet

add_filter(
	'hivepress/v1/forms/listing_buy',
	function($form){
		if(isset($form['fields']['_quantity'])){
			$form['fields']['_quantity']['min_value'] = 2;
			$form['fields']['_quantity']['default'] = 2;
		}
		
		return $form;
	},
	1000
);

Hi Yevhen,

Thanks for the code snippet. I meant to be able to set a different minimum quantity on each different product published.

The code snippet you provided works perfect but it establishes the same minimum quantity for all listings published.

Is it possible to have a MOQ for each individual product?

Please try to create a Number type listing attribute in the Listings/Attributes. Then please try to use this PHP code snippet. Please change get_put_attribute_field_name_here in the code snippet on get_ + your custom attribute field name

add_filter(
	'hivepress/v1/forms/listing_buy',
	function($fields, $form){
		$listing = $form->get_model();
		
		if(!$listing || !$listing->get_put_attribute_field_name_here()){
			return $fields;
		}

		if(isset($fields['fields']['_quantity'])){
			$fields['fields']['_quantity']['min_value'] = $listing->get_put_attribute_field_name_here();
			$fields['fields']['_quantity']['default'] = $listing->get_put_attribute_field_name_here();
		}
		
		return $fields;
	},
	1000,
	2
);
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.