Created
September 11, 2025 18:01
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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