“Bulk Edit WooCommerce Product Prices and Sale Prices”

code:

<?php
// Initialize the log file
$logFile = 'price_update_log.txt';
file_put_contents($logFile, date('Y-m-d H:i:s') . " - Script execution started\n", FILE_APPEND);

// Get the offset
$offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;

// Query product parameters
$args = [
    'post_type' => 'product',
    'posts_per_page' => 1,
    'offset' => $offset,
    'post_status' => 'publish',
    'orderby' => 'ID',
    'order' => 'DESC',
];

// Get products
$products = wc_get_products($args);
$count = count($products);

// Define a function to send a cURL request
function sendCurlRequest($url, $headers, $data, $consumer_key, $consumer_secret) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 240);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_USERPWD, "$consumer_key:$consumer_secret");

    $resp = curl_exec($curl);
    $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    if ($resp === false) {
        $error = curl_error($curl);
        curl_close($curl);
        return [
            'success' => false,
            'message' => "cURL request error: $error"
        ];
    }

    curl_close($curl);
    return [
        'success' => $status_code >= 200 && $status_code < 300,
        'message' => $resp
    ];
}

foreach ($products as $product) {
    $product_id = $product->get_id();
    if ($product->is_type('simple')) {
        // Process simple products
        $regular_price = $product->get_regular_price();
        // Assume there is a discount rate here, you can modify it according to the actual situation
        $discount_rate = 0.8; 
        $sale_price = $regular_price * $discount_rate;

        if (isset($sale_price) && !empty($sale_price)) {
            $product->set_sale_price($sale_price);
            $product->set_price($sale_price);
        } else {
            $product->set_price($regular_price);
        }
        $product->set_regular_price($regular_price);
        $product->save();

        $logMessage = $product_id . "-" . $regular_price . "-" . $sale_price . " Simple product processed!\n";
        file_put_contents($logFile, $logMessage, FILE_APPEND);
        echo $logMessage;
    } elseif ($product->is_type('variable')) {
        // Process variable products
        $regular_price = $product->get_variation_regular_price('min');
        // Assume there is a discount rate here, you can modify it according to the actual situation
        $discount_rate = 0.8; 
        $sale_price = $regular_price * $discount_rate;

        $variations = $product->get_available_variations();
        foreach ($variations as $variation) {
            $variation_id = $variation['variation_id'];
            $url = "https://yoursite.com/wp-json/wc/v3/products/" . $product_id . "/variations/" . $variation_id;
            $consumer_key = 'KEY';
            $consumer_secret = 'Secret';
            $headers = array(
                'Authorization' => 'Basic ' . base64_encode($consumer_key . ':' . $consumer_secret)
            );
            $data = array(
                'regular_price' => $regular_price,
                'sale_price' => $sale_price
            );

            $result = sendCurlRequest($url, $headers, $data, $consumer_key, $consumer_secret);
            if ($result['success']) {
                $logMessage = $product_id . "-" . $regular_price . "-" . $sale_price . " Variable product variation " . $variation_id . " processed!\n";
            } else {
                $logMessage = $product_id . "-" . $regular_price . "-" . $sale_price . " Variable product variation " . $variation_id . " processing failed: " . $result['message'] . "\n";
            }
            file_put_contents($logFile, $logMessage, FILE_APPEND);
            echo $logMessage;
        }
    }
}

// Jump to the next page
$offset = $offset + 1;
header("Refresh: 3; URL=?offset=" . $offset);
file_put_contents($logFile, date('Y-m-d H:i:s') . " - Script execution ended, offset: $offset\n", FILE_APPEND);
?>    

Code Explanation
Log Recording: The file_put_contents function is used to record information during the script execution in the price_update_log.txt file, which facilitates subsequent review and troubleshooting.
Pagination Logic: The current offset is obtained through $_GET[‘offset’]. After processing a batch of products each time, the offset is incremented by 1, and the script jumps to the next page for further processing via header(“Refresh: 3; URL=?offset=”.$offset);.
Error Handling: In the sendCurlRequest function, error handling for cURL requests is added to ensure that possible network request errors can be captured and recorded.
Code Reusability: The cURL request is encapsulated in the sendCurlRequest function, which improves the reusability and maintainability of the code.
Usage Instructions
Save the above code as a PHP file, for example, woocommerce_price_update.php.
Ensure that you have installed the WooCommerce plugin and configured the REST API keys in the WordPress backend.
Replace $consumer_key and $consumer_secret with your own API keys.
Replace https://yoursite.com with your own website domain.
Access the PHP file, and the script will start batch – modifying product prices and sale prices.
In this way, you can safely and efficiently batch – modify the prices and sale prices of WooCommerce products.

Share the Post:

Related Posts