MVTHEME
How to allow visitors to set a price for a product?
WordPress, WooCommerce

How to allow visitors to set a price for a product?

Millenium, May 15, 2023

For store owners using WooCommerce, a feature is available that allows shoppers to enter their own price on the product page. Let’s call it “dynamic price for the product”. This is useful for accepting donations, paying bills, or providing options for entering custom amounts.

To do this, you need to create a simple product with a price of $0 and paste the code snippet in functions.php, which you will find below. This will display an input field where buyers can enter their price. After the buyer has chosen a price, it will be automatically re-defined in the shopping cart, on the checkout page and in the order itself.

To use this feature, you need to create a simple product and get its ID so that you can specify it in your code. The name of the product can be anything, such as “Donation” or “Bill Payment”. Paste this code into your theme’s functions.php file.

add_action( 'woocommerce_before_add_to_cart_button', 'mvtheme_product_price_input', 9 );
  
function mvtheme_product_price_input() {
   global $product;
   //150891 - id product
   if ( 150891 !== $product->get_id() ) return;
   woocommerce_form_field( 'set_price', array(
      'type' => 'text',
      'required' => true,
      'label' => 'Set price ' . get_woocommerce_currency_symbol(),
   ));
}
  
add_filter( 'woocommerce_add_to_cart_validation', 'mvtheme_product_add_on_validation', 9999, 3 );
  
function mvtheme_product_add_on_validation( $passed, $product_id, $qty ) {
   if ( isset( $_POST['set_price'] ) && sanitize_text_field( $_POST['set_price'] ) == '' ) {
      wc_add_notice( 'Set price is a required field', 'error' );
      $passed = false;
   }
   return $passed;
}
  
add_filter( 'woocommerce_add_cart_item_data', 'mvtheme_product_add_on_cart_item_data', 9999, 2 );
  
function mvtheme_product_add_on_cart_item_data( $cart_item, $product_id ) {
   if ( 150891 !== $product_id ) return $cart_item;    
   $cart_item['set_price'] = sanitize_text_field( $_POST['set_price'] );
   return $cart_item;
}
 
add_action( 'woocommerce_before_calculate_totals', 'mvtheme_alter_price_cart', 9999 );
  
function mvtheme_alter_price_cart( $cart ) {
   if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
   if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
   foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
      $product = $cart_item['data'];
      if ( 150891 !== $product->get_id() ) continue;
      $cart_item['data']->set_price( $cart_item['set_price'] );
   } 
}

Leave a Reply

Your email address will not be published. Required fields are marked *