【发布时间】: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,您可以解码这些内容,将其作为数组保存在带有<?php return [....];的.php 文件中,然后使用包含。所以你可以跳过解码,如果你多次解码相同的东西,这会更有用(基本上将数据缓存为 PHP 数组,但这并不总是可行的。 -
@ArtisticPhoenix
define('WP_USE_THEMES', false)没有任何效果。json_decode只使用一次,所以我认为它不会有任何重大影响。感谢您的建议! -
$dealer_file 使用了多少内存?
-
那我认为是 WordPress 的对象缓存。在循环中尝试 wp_cache_flush()。
标签: php wordpress woocommerce memory-leaks