Skip to content

Instantly share code, notes, and snippets.

@tomjn
Last active February 21, 2020 06:35
Show Gist options
  • Save tomjn/6140909 to your computer and use it in GitHub Desktop.
Save tomjn/6140909 to your computer and use it in GitHub Desktop.
If you're thinking of using WP_Query, try using this iterator instead, cleaner boilerplate, auto-cleans up after itself
<?php
$pages = new query_loop( array(
'post_type' => 'page'
));
foreach( $pages as $id => $post ) {
the_title();
// etc...
}
// put this below in your functions.php:
/**
* WordPress Main Posts Loop Iterator
*/
class query_loop implements Iterator {
public function __construct( $args = array() ) {
$this->query = new WP_Query( $args );
}
function rewind() {
$this->query->rewind_posts();
}
function current() {
return $this->query->post;
}
function key() {
return $this->query->post->ID;
}
function next() {
$this->query->the_post();
}
function valid() {
if ( $this->query->have_posts() ) {
return true;
} else {
wp_reset_postdata();
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment