Skip to content

Instantly share code, notes, and snippets.

@barryhughes
Created September 11, 2025 18:01
Show Gist options
  • Save barryhughes/f50c34d196f12968005571a9c61aeb26 to your computer and use it in GitHub Desktop.
Save barryhughes/f50c34d196f12968005571a9c61aeb26 to your computer and use it in GitHub Desktop.
Simple example of a generator-based approach to iterating across the (WooCommerce) product catalog.
<?php
/**
* @return Generator<WC_Product>
*/
function fetch_all_products(): Generator {
$page = 1;
while ( true ) {
$products = wc_get_products( [
'limit' => 100,
'page' => $page++,
] );
if ( ! is_array( $products ) || empty( $products ) ) {
return;
}
foreach ( $products as $product ) {
yield $product;
}
}
}
// Iterate across the entire product catalog.
foreach ( fetch_all_products() as $product ) {
print $product->get_id() . ' ' . $product->get_name() . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment