How to hide or show price on a product in woocommerce?

David Beroff

Well-known member
Registered
Joined
Jun 14, 2016
Messages
1,488
Points
63
I am using woocommerce with WordPress and I want to have a check box for each product which I want to hide or show price depending on my decision. How can I do this with a custom code?
 

MooseLucifer

Well-known member
Registered
Joined
May 20, 2016
Messages
149
Points
28
To add a checkbox to your WooCommerce product edit page that can hide or show the product price, you can follow these steps:

Step 1: Add a custom meta field for the product You will need to add a custom meta field to your product edit page to store the value of whether or not to hide the price. You can do this by adding the following code to your functions.php file:

Code:
add_action( 'woocommerce_product_options_pricing', 'add_hide_price_checkbox' );
function add_hide_price_checkbox() {
global $woocommerce, $post;
echo '<div class="options_group">';
woocommerce_wp_checkbox(
array(
'id' => 'hide_price',
'wrapper_class' => 'show_if_simple',
'label' => __('Hide Price', 'woocommerce' ),
'description' => __('Check this box to hide the price of the product on the front-end.', 'woocommerce' )
)
);
echo '</div>';
}

This code adds a checkbox field to the product pricing options that will store the value of whether or not to hide the price.

Step 2: Save the meta field value You need to save the value of the checkbox in the custom meta field. You can do this by adding the following code to your functions.php file:

Code:
add_action( 'woocommerce_process_product_meta', 'save_hide_price_checkbox' );
function save_hide_price_checkbox( $post_id ) {
$hide_price = isset( $_POST['hide_price'] ) ? 'yes' : 'no';
update_post_meta( $post_id, 'hide_price', $hide_price );
}
This code saves the value of the checkbox as a custom meta field named hide_price.

Step 3: Hide or show the price based on the checkbox value Finally, you need to modify the product price output based on the checkbox value. You can do this by adding the following code to your functions.php file:

Code:
add_filter( 'woocommerce_get_price_html', 'hide_price_based_on_checkbox', 100, 2 );
function hide_price_based_on_checkbox( $price, $product ) {
if ( 'yes' === get_post_meta( $product->get_id(), 'hide_price', true ) ) {
$price = '';
}
return $price;
}
This code filters the product price output and hides the price if the checkbox value is set to "yes".

With these steps, you will now have a checkbox on your product edit page that can hide or show the product price based on your decision.
 
Older Threads
Replies
4
Views
761
Replies
1
Views
626
Replies
0
Views
464
Utx

Latest Hosting OffersNew Reviews

Sponsors

Tag Cloud

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top