I want to have third price available in WooCommerce:
- Regular price
- Discounted price
- Super Sale Price
So far I added it in the admin area and frontend to be visible, but whatever I try I can’t make it work with cart, because I need it to check from 3, to one, like: If there is option 3 (Super Sale PRice), make that price, if there is 2 (Discounted price) make that price, if there is 1 (Regular price only), make that price.
And all of this should not mess up with variable products and be only for simple products.
Here is my code:
/**
* Function to render UI in Admin Product add/edit page
*/
function show_custom_price_admin() {
global $thepostid;
woocommerce_wp_text_input(
array(
'id' => 'custom_price',
'name' => '_custom_price',
'value' => get_post_meta( $thepostid, '_custom_price', true ),
'class' => 'wc_input_price short',
'label' => __( 'Custom Price ($)', 'vg' ),
)
);
}
add_action( 'woocommerce_product_options_pricing', 'show_custom_price_admin' );
/**
* Function to update custom price Admin Product add/edit page
*
* @param int $post_id Product's post id.
*/
function process_product_custom_data( $post_id ) {
$product = wc_get_product( $post_id );
$product->update_meta_data(
'_custom_price',
wc_clean( wp_unslash( filter_input( INPUT_POST, '_custom_price' ) ) )
);
$product->save();
}
add_action( 'woocommerce_process_product_meta', 'process_product_custom_data' );
/**
* Function to show custom price front end page
*/
function show_custom_price_frontend() {
global $post;
$custom_price = get_post_meta( $post->ID, '_custom_price', true );
if ( $custom_price ) {
$custom_price = wc_price( $custom_price );
printf( '<p class="price">%s</p>', $custom_price );
}
}
add_action( 'woocommerce_before_add_to_cart_form', 'show_custom_price_frontend' );
So far I added it in the admin area and frontend to be visible, but whatever I try I can’t make it work with cart, because I need it to check from 3, to one, like: If there is option 3 (Super Sale PRice), make that price, if there is 2 (Discounted price) make that price, if there is 1 (Regular price only), make that price.
And all of this should not mess up with variable products and be only for simple products.
2
Answers
Your code is a bit outdated, and there are some missing things. To set and display a custom price (if it is defined in the backend, for simple products), try the following:
Code goes in functions.php file of your child theme (or in a plugin). Now it will work.
There are some issues with your hooks. I tested this code it’s working. Put it in child-theme’s functions.php file.
@LoicTheAztec answer is right you can also try his code if this code does not works.
Happy Coding!!