Created
July 2, 2020 13:56
-
-
Save paulgibbs/b29b0b354b21d1a4d771b646f474457e to your computer and use it in GitHub Desktop.
php generators example
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 | |
/** | |
* 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