Last active
December 22, 2015 19:39
-
-
Save hakre/6520715 to your computer and use it in GitHub Desktop.
WP_Query_Posts_Iterator - External Iterator for posts of WP_Query
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 | |
/** | |
* 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