Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active October 12, 2015 16:45
Show Gist options
  • Save westonruter/9d1c1b9d782fa8d86df3 to your computer and use it in GitHub Desktop.
Save westonruter/9d1c1b9d782fa8d86df3 to your computer and use it in GitHub Desktop.
<?php
/**
* Generator for get_posts().
*
* @see \get_posts()
* @param $args
* @return \Generator
*/
function all_posts( $args = array() ) {
$posts_per_page = 100; // @todo Allow $args to contain a $posts_per_page which we can chunk to arrive at.
$paged = 1;
foreach ( array( 'posts_per_page', 'page', 'no_found_rows' ) as $arg ) {
if ( isset( $args[ $arg ] ) ) {
throw new \LogicException( "Illegal arg: $arg" );
}
}
do {
$posts = get_posts( array_merge(
array(
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'no_found_rows' => true,
),
$args
) );
foreach ( $posts as $post ) {
yield $post;
}
$paged += 1;
// @todo Maybe stop_the_insanity here if we notice available memory is getting low
} while ( ! empty( $posts ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment