csv PHP Uploader for WooCommerce未提取新信息

wwodge7n  于 2023-07-31  发布在  PHP
关注(0)|答案(1)|浏览(68)

我使用一个由cron触发的PHP脚本来更新产品价格和其他一些信息。它涉及将CSV文件放置在文件夹中并运行脚本以自动更新。我遇到了一个问题,我只能在编辑产品部分看到更改。新的信息只拉一次我点击“更新”按钮。考虑到我有68,000产品更新的时间,我需要的PHP脚本是强制刷新的信息。有什么想法吗?任何帮助都很感激。

<?php
// Load WordPress environment
require_once('wp-load.php');

// Set the maximum execution time for the script (in seconds)
$maxExecutionTime = 120; // Adjust the value as needed

// Path to the CSV uploads folder
$csvUploadsPath = __DIR__ . '/CSVUploads/';

// Create the log directory if it doesn't exist
$logDirectory = $csvUploadsPath . 'log/';
if (!is_dir($logDirectory)) {
    mkdir($logDirectory, 0755, true);
}

// Get all CSV files in the uploads folder
$csvFiles = glob($csvUploadsPath . '*.csv');

// Process each CSV file
foreach ($csvFiles as $csvFile) {
    // Log the timestamp and file being processed
    $logFilePath = $logDirectory . basename($csvFile) . '.log';
    file_put_contents($logFilePath, '[' . date('Y-m-d H:i:s') . '] Processing file: ' . $csvFile . PHP_EOL, FILE_APPEND);

    // Get the last savepoint for this CSV file
    $savepointIndex = 0;
    if (file_exists($logFilePath)) {
        $logContents = file_get_contents($logFilePath);
        $logData = unserialize($logContents);
        if (is_array($logData) && isset($logData['savepointIndex'])) {
            $savepointIndex = intval($logData['savepointIndex']);
        }
    }

    // Import products from the CSV file
    if (($handle = fopen($csvFile, 'r')) !== false) {
        // Skip the header row
        $header = fgetcsv($handle);

        // Store the start time
        $startTime = time();

        // Skip rows until reaching the savepoint index
        for ($i = 0; $i < $savepointIndex; $i++) {
            fgetcsv($handle);
        }

        // Process each remaining data row
        $currentIndex = $savepointIndex;
        while (($data = fgetcsv($handle)) !== false) {
            $currentIndex++;

            // Extract the necessary fields from the CSV row
            $sku = $data[2];
            $price = $data[14];
            $tradeInValue = $data[63];
            $stockQuantity = $data[8];
            $visibility = $data[58];

            // Search for the product by SKU
            $existingProduct = get_posts(array(
                'post_type' => 'product',
                'meta_key' => '_sku',
                'meta_value' => $sku,
                'post_status' => 'publish',
                'posts_per_page' => 1
            ));

            if (!empty($existingProduct)) {
                // Product found, update its price, trade-in value, stock quantity, and visibility
                $productID = $existingProduct[0]->ID;

                // Update the product price
                update_post_meta($productID, '_regular_price', $price);
                update_post_meta($productID, '_price', $price);

                // Update the trade-in value as custom meta field
                update_post_meta($productID, 'trade_in', $tradeInValue);

                // Update the stock quantity
                update_post_meta($productID, '_stock', $stockQuantity);

                // Update the visibility in the catalog
                update_post_meta($productID, '_visibility', $visibility);

        // Trigger WooCommerce product update actions
                do_action('woocommerce_product_object_updated_props', $productID);
        
        // Trigger the product save action
        do_action('woocommerce_product_save', $productID);


                // Log the success message
                file_put_contents($logFilePath, '[' . date('Y-m-d H:i:s') . '] Updated product with SKU ' . $sku . PHP_EOL, FILE_APPEND);
            } else {
                // Product not found, log the error message
                file_put_contents($logFilePath, '[' . date('Y-m-d H:i:s') . '] Error: Product with SKU ' . $sku . ' not found.' . PHP_EOL, FILE_APPEND);
            }

            // Check the remaining time during each iteration
            $remainingTime = $maxExecutionTime - (time() - $startTime);
            if ($remainingTime < 3) {
                // Save the current progress
                $logData = array('savepointIndex' => $currentIndex);
                $logContents = serialize($logData);
                file_put_contents($logFilePath, $logContents);

                // Redirect to the same script to resume the execution
                header('Location: ' . $_SERVER['PHP_SELF']);
                exit;
            }

            // Create a savepoint every 100 lines
            if ($currentIndex % 100 === 0) {
                $logData = array('savepointIndex' => $currentIndex);
                $logContents = serialize($logData);
                file_put_contents($logFilePath, $logContents);
            }
        }

        fclose($handle);

        // Delete the CSV file after processing
        unlink($csvFile);

        // Remove the log file
        if (file_exists($logFilePath)) {
            unlink($logFilePath);
        }

        // Clear or refresh transients
        global $wpdb;
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '\_transient\_%' OR option_name LIKE '\_site\_transient\_%'");
    } else {
        // Log the error message if unable to open the CSV file
        file_put_contents($logFilePath, '[' . date('Y-m-d H:i:s') . '] Error: Failed to open CSV file.' . PHP_EOL, FILE_APPEND);
    }
}
?>

字符串
预期脚本会更新产品价格,它确实更新了,但新信息并没有出现

neskvpey

neskvpey1#

要在PHP脚本中更新产品信息后强制刷新,可以使用WordPress提供的wp_cache_flush()函数。
以下是如何修改代码以包含该高速缓存刷新:

// Load WordPress environment
require_once('wp-load.php');

// Set the maximum execution time for the script (in seconds)
$maxExecutionTime = 120; // Adjust the value as needed

// Path to the CSV uploads folder
$csvUploadsPath = __DIR__ . '/CSVUploads/';

// Create the log directory if it doesn't exist
$logDirectory = $csvUploadsPath . 'log/';
if (!is_dir($logDirectory)) {
    mkdir($logDirectory, 0755, true);
}

// Get all CSV files in the uploads folder
$csvFiles = glob($csvUploadsPath . '*.csv');

// Process each CSV file
foreach ($csvFiles as $csvFile) {
    // Log the timestamp and file being processed
    $logFilePath = $logDirectory . basename($csvFile) . '.log';
    file_put_contents($logFilePath, '[' . date('Y-m-d H:i:s') . '] Processing file: ' . $csvFile . PHP_EOL, FILE_APPEND);

    // Get the last savepoint for this CSV file
    $savepointIndex = 0;
    if (file_exists($logFilePath)) {
        $logContents = file_get_contents($logFilePath);
        $logData = unserialize($logContents);
        if (is_array($logData) && isset($logData['savepointIndex'])) {
            $savepointIndex = intval($logData['savepointIndex']);
        }
    }

    // Import products from the CSV file
    if (($handle = fopen($csvFile, 'r')) !== false) {
        // Skip the header row
        $header = fgetcsv($handle);

        // Store the start time
        $startTime = time();

        // Skip rows until reaching the savepoint index
        for ($i = 0; $i < $savepointIndex; $i++) {
            fgetcsv($handle);
        }

        // Process each remaining data row
        $currentIndex = $savepointIndex;
        while (($data = fgetcsv($handle)) !== false) {
            $currentIndex++;

            // Extract the necessary fields from the CSV row
            $sku = $data[2];
            $price = $data[14];
            $tradeInValue = $data[63];
            $stockQuantity = $data[8];
            $visibility = $data[58];

            // Search for the product by SKU
            $existingProduct = get_posts(array(
                'post_type' => 'product',
                'meta_key' => '_sku',
                'meta_value' => $sku,
                'post_status' => 'publish',
                'posts_per_page' => 1
            ));

            if (!empty($existingProduct)) {
                // Product found, update its price, trade-in value, stock quantity, and visibility
                $productID = $existingProduct[0]->ID;

                // Update the product price
                update_post_meta($productID, '_regular_price', $price);
                update_post_meta($productID, '_price', $price);

                // Update the trade-in value as custom meta field
                update_post_meta($productID, 'trade_in', $tradeInValue);

                // Update the stock quantity
                update_post_meta($productID, '_stock', $stockQuantity);

                // Update the visibility in the catalog
                update_post_meta($productID, '_visibility', $visibility);

                // Trigger WooCommerce product update actions
                do_action('woocommerce_product_object_updated_props', $productID);
                do_action('woocommerce_product_save', $productID);

                // Flush the cache for the updated product
                wp_cache_flush();

                // Log the success message
                file_put_contents($logFilePath, '[' . date('Y-m-d H:i:s') . '] Updated product with SKU ' . $sku . PHP_EOL, FILE_APPEND);
            } else {
                // Product not found, log the error message
                file_put_contents($logFilePath, '[' . date('Y-m-d H:i:s') . '] Error: Product with SKU ' . $sku . ' not found.' . PHP_EOL, FILE_APPEND);
            }

            // Check the remaining time during each iteration
            $remainingTime = $maxExecutionTime - (time() - $startTime);
            if ($remainingTime < 3) {
                // Save the current progress
                $logData = array('savepointIndex' => $currentIndex);
                $logContents = serialize($logData);
                file_put_contents($logFilePath, $logContents);

                // Redirect to the same script to resume the execution
                header('Location: ' . $_SERVER['PHP_SELF']);
                exit;
            }

            // Create a savepoint every 100 lines
            if ($currentIndex % 100 === 0) {
                $logData = array('savepointIndex' => $currentIndex);
                $logContents = serialize($logData);
                file_put_contents($logFilePath, $logContents);
            }
        }

        fclose($handle);

        // Delete the CSV file after processing
        unlink($csvFile);

        // Remove the log file
        if (file_exists($logFilePath)) {
            unlink($logFilePath);
        }

        // Clear or refresh transients
        global $wpdb;
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '\_transient\_%' OR option_name LIKE '\_site\_transient\_%'");
    } else {
        // Log the error message if unable to open the CSV file
        file_put_contents($logFilePath, '[' . date('Y-m-d H:i:s') . '] Error: Failed to open CSV file.' . PHP_EOL, FILE_APPEND);
    }
}

字符串
在此更新的代码中,在更新每个产品后,调用wp_cache_flush()函数来清除更新产品该高速缓存。这将确保更新的信息立即反映在前端。
请注意,该高速缓存可能会影响性能,因此请确保评估对服务器资源的影响,并根据需要相应地调整代码。

相关问题