我需要以编程方式更新大约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。 有没有办法进一步减少内存使用?
答案 0 :(得分:0)
问题在于使用wc_update_product_stock()
来更新库存。
代替它,现在我使用:
update_post_meta($post_id, '_stock', 'stock_number');
总体使用情况为30MB以下,这是IMO的出色表现。