I Would like to replace all Regular prices on my WooCommerce store with the Sale Price value and delete the Sale Price values under the wp_postmeta
Here is a custom function that will copy the sale price to the regular price and will reset the sale price.Regarding the prices in WooCommerce there is:
'_price''_regular_price''_sale_price'So you need to update the regular price too and to reset all related data for the sale price. Also you need to refresh prices.
This function has an UI that will appear in shop pages or single product pages only for Admins and Shop Manager.
If you have more than 1000 products, the process will be auto split in multiple steps (by 1000 products) to avoid errors when there is too many products.
The SQL query will only select products Ids that have a sale price and not all products. To update/Reset prices I use update_post_meta() function instead of a query, to refresh each product cache...
It looks like:
Important: Before starting this kind of process always make a database backup
Here is that hooked function code:
add_action( 'woocommerce_before_main_content', function(){
// Only admins and shop manargers
if( ! current_user_can( 'edit_products' ) ) return;
global $wpdb;
$products_count = get_option( 'product_prices_update_count' );
// Auto enable multistep price updates for more than 1000 products
$limit = $products_count > 2 ? 2 : false;
if( $limit != false )
$offset = get_option( 'product_prices_update_offset' );
if( empty( $offset ) && $limit != false ) {
$offset = 0;
add_option( 'product_prices_update_offset', $offset );
}
$control_process = $limit != false ? "LIMIT $offset, $limit" : "";
if( ! isset( $_POST['prices_updates'] ) ) $control_process = '';
// 1. First query: Get for all product ids the sale price
$results = $wpdb->get_results( "
SELECT postmeta.post_id, postmeta.meta_value as price
FROM {$wpdb->prefix}postmeta as postmeta
INNER JOIN {$wpdb->prefix}posts as posts ON postmeta.post_id = posts.ID
WHERE posts.post_type LIKE '%product%'
AND postmeta.meta_key = '_sale_price'
AND postmeta.meta_value != ''
ORDER BY posts.ID ASC
$control_process
" );
if( empty( $products_count ) ){
update_option( 'product_prices_update_count', count($results) );
$count = count($results);
} else $count = $products_count;
$remaining = ! empty( $products_count ) && $limit != false ? $count-($offset+$limit) : count($results);
$products_updated = 0;
echo '
';
}, 2, 0);
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works.