Skip to content

Instantly share code, notes, and snippets.

@sheabunge
Last active March 18, 2020 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sheabunge/4b0cb86b5193645d6efa94b09290b819 to your computer and use it in GitHub Desktop.
Save sheabunge/4b0cb86b5193645d6efa94b09290b819 to your computer and use it in GitHub Desktop.
WordPress loop generator function, as described at https://wpscholar.com/blog/creating-better-wordpress-loop/
<?php
/**
* Simplifies the WordPress loop.
*
* @param WP_Query|WP_Post[] $iterable
*
* @return Generator
*/
function wp_loop( $iterable = null ) {
if ( null === $iterable ) {
$iterable = $GLOBALS['wp_query'];
}
$posts = $iterable;
if ( is_object( $iterable ) && property_exists( $iterable, 'posts' ) ) {
$posts = $iterable->posts;
}
if ( ! is_array( $posts ) ) {
throw new \InvalidArgumentException( sprintf( 'Expected an array, received %s instead', gettype( $posts ) ) );
}
global $post;
// Save the global post object so we can restore it later
$save_post = $post;
try {
foreach ( $posts as $post ) {
setup_postdata( $post );
yield $post;
}
} finally {
wp_reset_postdata();
// Restore the global post object
$post = $save_post;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment