John Davidson

wordpress - Is there any way to add a pause after so many iterations in a php foreach loop?

0 comments
Message:


I'm trying to update post meta for over 100,000 WooCommerce products (using ACF's update_field function). The code is pretty straightforward, it assigns a priority order based on the menu order of an attribute. Since it's going through so many products, the memory limit gets reached. Is there maybe a way to pause for a few seconds after every 1,000 records so that the memory limit doesn't get exhausted?


  $args = array(
'taxonomy' => 'pa_brand',
'hide_empty' => false,
);
$brands = get_terms("pa_brand");
$brand_IDs = array();
foreach ($brands as $brand) {
array_push($brand_IDs, $brand->term_id);
}




$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
);
$products = get_posts($args);

// This is the foreach loop that goes through thousands of products
foreach ($products as $prod) {
$ID = $prod->ID;
$brand = get_the_terms($ID, 'pa_brand');
$brand = $brand[0] ?? false;
if (!$brand) {
continue;
}
$brand_ID = $brand->term_id;
$priority = array_search($brand_ID, $brand_IDs) + 1;

update_field("field_61607fa7967c4", $priority, $ID);
}

I've confirmed the code does work properly. I tried on just 5 products.



My Answer:
> One way to add a pause after a certain number of iterations in a PHP foreach loop is to use the sleep() function. You can add a condition inside your loop to check the iteration count and then use the sleep() function to pause for a few seconds.

Here's an example of how you can modify your code to add a pause after every 1,000 records:

php
$args = array(
'taxonomy' => 'your_taxonomy_here',
'hide_empty' => false,
);

$terms = get_terms($args);

$counter = 0;

foreach ($terms as $term) {
// Your code to update post meta here

$counter++;

if ($counter % 1000 == 0) {
// Pause for 3 seconds after every 1,000 records
sleep(3);
}
}


This code will pause for 3 seconds after every 1,000 records processed in the foreach loop. Adjust the sleep time as needed based on your requirements. This should help prevent memory exhaustion by giving the system some time to release memory before continuing with the next batch of records.

Rate this post

5 of 5 based on 3999 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us