Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Updates product prices via WP CLI script.
<?php
/**
* Updates product prices.
* More about WP CLI scripts:
* https://wptheming.com/2021/05/wp-cli-scripts-and-woocommerce/
*
* wp eval-file update-product-prices.php
*/
$products = get_posts([
'post_type' => [ 'product' ],
'posts_per_page' => -1,
'fields' => 'ids',
]);
// Amount of price change.
$price_change = 1.00;
// Headers to log in csv output.
$headers = [ 'id', 'title', 'original price', 'updated price' ];
log_data( $headers );
// Output for terminal.
$output = array();
WP_CLI::log( "" );
$progress = \WP_CLI\Utils\make_progress_bar( 'Updating prices', count( $products ) );
foreach ( $products as $product_id ) {
$data = [];
$product = wc_get_product( $product_id );
$original_price = $product->get_regular_price();
$updated_price = $original_price + $price_change;
$product->set_regular_price( $updated_price );
$product->save();
$data['id'] = $product_id;
$data['title'] = $product->get_title();
$data['original price'] = wc_format_decimal( $original_price, 2);
$data['updated price'] = wc_format_decimal( $updated_price, 2);
$output[] = $data;
log_data( $data );
$progress->tick();
}
$progress->finish();
WP_CLI::log( "" );
\WP_CLI\Utils\format_items( 'table', $output, $headers );
WP_CLI::log( "" );
function log_data( $output ) {
$file_name = 'export-data.csv';
$file_resource = fopen( $file_name, 'a' );
fputcsv( $file_resource, $output );
fclose( $file_resource );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment