Last active
June 27, 2022 00:10
-
-
Save mrizwan47/24061263dc47be0d30483c1dd08f78f6 to your computer and use it in GitHub Desktop.
Change woocommerce sales price programmatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Your Product ID | |
$product_id = 57; | |
$ecd_product = new WC_Product( $product_id ); | |
/** | |
* Check if product exists | |
*/ | |
if( $ecd_product->exists() ){ | |
/** | |
* Get current (discounted) sales price for calculations etc | |
*/ | |
$ecd_product->sale_price; | |
/** | |
* Get regular price for calculations etc | |
*/ | |
$ecd_product->regular_price; | |
/** | |
* Get price (the actually price that people will pay) | |
* NOTE: If you set sales price different, this should be same as sales price | |
*/ | |
$ecd_product->price; | |
/** | |
* Update sales price to $10 | |
*/ | |
$sp = update_post_meta( $ecd_product->id, '_sale_price', '10' ); | |
$p = update_post_meta( $ecd_product->id, '_price', '10' ); | |
$rp = update_post_meta( $ecd_product->id, '_regular_price', '10' ); | |
if( $sp && $p ){ | |
echo 'Sales price is $10 now!'; | |
} | |
} |
thanks mate
Better add one more update_post_meta
with _regular_price
because wp_postmeta
contains 3 prices: _price
, _sale_price
, _regular_price
like this:
$rp = update_post_meta( $ecd_product->id, '_regular_price', '10' );
incomplete function, i think it is, to which hook it should be hooked in woocommerce
This code worked for me
I had to update and set static price for every single product in woocommerce.
add_action( 'added_post_meta', 'ij_set_default_report_price', 10, 4 );
add_action( 'updated_post_meta', 'ij_set_default_report_price', 10, 4 );
function ij_set_default_report_price( $meta_id, $post_id, $meta_key, $meta_value ) {
if ( $meta_key == '_edit_lock' ) { // we've been editing the post
if ( get_post_type( $post_id ) == 'product' ) { // we've been editing a product
$product = wc_get_product( $post_id );
if($product){
$rp = update_post_meta( $product->id, '_regular_price', '4200' );
update_post_meta($product->id, '_price', '4200');
}
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perfect code