Skip to content

Instantly share code, notes, and snippets.

@pmgarman
Created March 15, 2019 16:02
Show Gist options
  • Save pmgarman/bc89cd93da321335fca634f52d77d0ed to your computer and use it in GitHub Desktop.
Save pmgarman/bc89cd93da321335fca634f52d77d0ed to your computer and use it in GitHub Desktop.
Old code for WC 2.x to set a flash sale price on all products.
<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Check if WP_CLI exists, and only extend it if it does
if ( defined( 'WP_CLI' ) && WP_CLI && ! class_exists( 'CP_CLI' ) ) {
/**
* Class CP_CLI
*/
class CP_CLI extends WP_CLI_Command {
public function flashsale( $args, $assoc_args ) {
global $wpdb;
$rate = isset( $assoc_args['rate'] ) ? absint( $assoc_args['rate'] ) : 20;
$sale = absint( $rate ) / 100;
$products = $wpdb->get_col( "select ID from {$wpdb->posts} where post_type = 'product';" );
foreach( $products as $product_id ) {
$product = wc_get_product( $product_id );
// Don't flash sale products on sale already
if( $product->is_on_sale() ) {
continue;
}
$regular_price = $product->get_regular_price();
$sale_price = $regular_price - ( $sale * $regular_price );
update_post_meta( $product_id, '_price', $sale_price );
update_post_meta( $product_id, '_sale_price', $sale_price );
}
}
}
WP_CLI::add_command( 'cp', 'CP_CLI' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment