Skip to content

Instantly share code, notes, and snippets.

@hakre
Last active December 22, 2015 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hakre/6520715 to your computer and use it in GitHub Desktop.
Save hakre/6520715 to your computer and use it in GitHub Desktop.
WP_Query_Posts_Iterator - External Iterator for posts of WP_Query
<?php
/**
* Class WP_Query_Posts_Iterator
*
* External Iterator for posts of WP_Query.
*/
class WP_Query_Posts_Iterator implements iterator {
/**
* @var WP_Query
*/
private $query;
/**
* @var int|NULL
*/
private $index;
/**
* @var WP_Post|NULL
*/
private $post;
function __construct(WP_Query $query) {
$this->query = $query;
}
/**
* @return WP_Query
*/
public function getQuery() {
return $this->query;
}
public function rewind() {
$this->index = 0;
$this->setCurrentPost();
}
public function valid() {
$count = (int) $this->query->post_count;
return $count > 0 and $this->index < $count;
}
/**
* @return WP_Post
*/
public function current() {
return $this->post;
}
public function key() {
return $this->index;
}
public function next() {
if ($this->valid() and ++$this->index) {
$this->setCurrentPost();
}
}
private function setCurrentPost() {
$has = $this->index < (int) $this->query->post_count;
$this->post = $has ? $this->query->posts[$this->index] : NULL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment