Skip to content

Instantly share code, notes, and snippets.

@paulgibbs
Created July 2, 2020 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulgibbs/b29b0b354b21d1a4d771b646f474457e to your computer and use it in GitHub Desktop.
Save paulgibbs/b29b0b354b21d1a4d771b646f474457e to your computer and use it in GitHub Desktop.
php generators example
<?php
/**
* Plugin Name: Paul Test
*/
namespace PaulGibbs;
use Generator;
use WP_Query;
/**
* A generator for WP_Query/get_posts().
*
* @param array $args Options for WP_Query.
* @param int $page_offset Results pagination offset. Passed by reference.
*
* @return Generator Yields a result from WP_Query.
*/
function get_many_posts( array $args, int &$page_offset = 0 ) : Generator {
$query = new WP_Query();
while ( $page_offset === 1 || $query->paged < $query->max_num_pages ) {
yield $query->query( array_merge( $args, [ 'paged' => $page_offset ] ) );
$page_offset++;
}
return;
}
add_action(
'init',
function() {
$page = 1;
$args = [
'posts_per_page' => 5,
];
foreach ( get_many_posts( $args, $page ) as $posts ) {
echo '<p>Query results:</p><ul>';
foreach ( $posts as $post ) {
printf( '<li>ID: %d</li>', $post->ID );
}
echo '</ul></p>';
}
die;
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment