【问题标题】:Woocommerce - Hight memory usage when programmatically updating product variationsWoocommerce - 以编程方式更新产品变体时内存使用率高
【发布时间】:2019-04-04 02:46:55
【问题描述】:

我需要以编程方式更新大约 7000 个产品变体。

我已经尝试了几种解决方案并获得了最佳性能(感谢https://wordpress.stackexchange.com/questions/189371/how-to-solve-suspected-memory-issue-in-custom-wordpress-loop):

<?php

require_once("wp-load.php");

$dealer_file = json_decode(file_get_contents('file.json'), true);

$args = array(
    'fields'         => 'ids',
    'posts_per_page' => 10, 
    'post_type'      => array('product_variation'),
    'post_status'    => 'publish',
);

$query = new WP_Query;
$paged = 1;
$count = 0;
$total = null;

do {
    $args['no_found_rows'] = isset( $total );
    $args['paged'] = $paged++;

    $post_ids = $query->query( $args );
    update_postmeta_cache( $post_ids );

    if ( ! isset( $total ) )
        $total = $query->found_posts;

    $count += $query->post_count;

    foreach ( $post_ids as $post_id ) {
        $sku = get_post_meta( $post_id, '_sku', true );

        if(!empty($sku)) {
            if ( array_key_exists( $sku, $dealer_file ) ) {
                wc_update_product_stock( $post_id, $dealer_file[ $sku ]['stock_info'] );
                echo memory_get_usage(true).'<br>';
            }
            else {
                //Log function
            }
        }

        // Wipe this post's meta from memory
        wp_cache_delete( $post_id, 'posts' );
        wp_cache_delete( $post_id, 'post_meta' );
    }

} while ( $count < $total );

?>

使用这种方法,我使用了大约 600MB 的内存(我的代码是 800MB)。 我已经升级到 PHP 7。 有没有办法进一步减少内存使用?

【问题讨论】:

  • 我唯一看到的是添加这个define('WP_USE_THEMES', false) 来关闭主题支持,如果这是作为后台作业运行的,那么 WP 将不会加载主题文件。您可以减少每页的帖子,这可能会减少内存占用,但需要更长的时间。
  • 另一个命中来自json_decode,您可以解码这些内容,将其作为数组保存在带有&lt;?php return [....]; 的.php 文件中,然后使用包含。所以你可以跳过解码,如果你多次解码相同的东西,这会更有用(基本上将数据缓存为 PHP 数组,但这并不总是可行的。
  • @ArtisticPhoenix define('WP_USE_THEMES', false) 没有任何效果。 json_decode 只使用一次,所以我认为它不会有任何重大影响。感谢您的建议!
  • $dealer_file 使用了多少内存?
  • 那我认为是 WordPress 的对象缓存。在循环中尝试 wp_cache_flush()。

标签: php wordpress woocommerce memory-leaks


【解决方案1】:

问题在于使用wc_update_product_stock() 更新库存。 而不是它,现在我使用:

update_post_meta($post_id, '_stock', 'stock_number');

总体使用量低于 30MB,这在 IMO 方面非常出色。

【讨论】:

  • 这很危险,因为您现在正在绕过 WoCommerce API,并且不会触发操作/过滤器挂钩。例如,当库存变化时,库存状态会更新。如果您直接更新数据库,则可能会造成不一致,因为其他相关的数据库字段将不会更新。使用 API 可确保更新所有相关字段。
  • WooCommerce API 本质上对所有其他插件和主题做出了承诺。特别是在这里,它承诺当变体的库存发生变化时,将执行“woocommerce_variation_set_stock”操作。如果你绕过 API 并直接更新 '_stock' 数据库字段,你就违背了这个承诺。即使目前没有任何东西使用这个承诺,你将来可能会安装一个插件,它会神秘地不起作用。绕过 API 是一种不好的做法。
  • #realanswerisinthecmets
猜你喜欢
  • 2019-01-27
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 2023-01-30
相关资源
最近更新 更多