Set a Default Price for Products

Hammers which all looks the same

When you create a new product, by default WooCommerce leaves the price empty, and if you don't set one, the product will be considered free.

There might be cases where you do not want to manually set a price, but still do not leave it empty. Setting a default value would be the solution.

How can you do it with WooCommerce?

With custom code, of course!

Open your favourite code editor and edit the file functions.php in wp-content/themes/your-child-theme-name/ adding this code at the end:


/**
* Sets the product default price to 10. Only works once, if the price is not specified.
*
* @param int $post_id
* @param object $post
*/
function set_product_default_price( $post_id, $post ) {
$product = wc_get_product( $post_id );
$already_set = get_post_meta( $post_id, '_set_default_price', true );
$price = $product->get_price();
if ( 'yes' !== $already_set && empty( $price ) ) {
$product->set_regular_price( '10' );
$product->save();
update_post_meta( $post_id, '_set_default_price', 'yes' );
}
}
add_action( 'woocommerce_process_product_meta', 'set_product_default_price', 999, 2 );

view raw

functions.php

hosted with ❤ by GitHub

This script will set the product price to 10. It only runs once, if the product does not have the meta _set_default_price set to yes, and if a product price has not been specified already.

Be careful with products created before this snippet has been added to your site. If they don't have a price set the default price will be applied.


More Posts That You Might Like…


2 responses to “Set a Default Price for Products”

  1. Thank you for this.

  2. how would you add to this to get it to add the default of $10 to your variations? This is where I need it the most.

Leave a Reply

Categories

Newsletter

Receive new articles from this blog directly in your inbox!

No spam guaranteed!

Blog at WordPress.com.

%d bloggers like this: