Last active
February 21, 2020 06:35
-
-
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
This file contains 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 | |
$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