Skip to content

Instantly share code, notes, and snippets.

@apsolut
Forked from devinsays/update-product-prices.php
Created December 8, 2021 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apsolut/9997a18374c41e934856130f0dd4c23e to your computer and use it in GitHub Desktop.
Save apsolut/9997a18374c41e934856130f0dd4c23e to your computer and use it in GitHub Desktop.
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