Last active
December 20, 2015 10:48
-
-
Save felipelavinz/6117798 to your computer and use it in GitHub Desktop.
Create Entries Options using an ArrayIterator
This file contains hidden or 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 EntriesOptions extends ArrayIterator{ | |
private $query; | |
private $cur_post; | |
public function __construct( $query_params = array(), $flags = array() ){ | |
$args = wp_parse_args( $query_params, array( | |
'post_status' => 'publish', | |
'orderby' => 'title', | |
'order' => 'ASC', | |
'posts_per_page' => -1 | |
)); | |
$flags = wp_parse_args( $flags, array( | |
'show_option_none' => false | |
)); | |
$this->query = new WP_Query( $args ); | |
if ( $flags['show_option_none'] !== false ) { | |
array_unshift($this->query->posts, (object)array( | |
'ID' => '', | |
'post_title' => is_string($flags['show_option_none']) ? $flags['show_option_none'] : '(Ninguna)' | |
)); | |
} | |
parent::__construct( $this->query->posts ); | |
} | |
public function current(){ | |
$this->cur_post = parent::current(); | |
return $this->cur_post->post_title; | |
} | |
public function key(){ | |
$key = parent::key(); | |
return $this->query->posts[$key]->ID; | |
} | |
public function getArrayCopy(){ | |
$array = array(); | |
foreach ( $this->query->posts as $post ){ | |
$array[ $post->ID ] = $post->post_title; | |
} | |
return $array; | |
} | |
} | |
// usage: | |
$articles_options = new EntriesOptions(array( | |
'post_type' => 'article', | |
'posts_per_page' => 5 | |
)); | |
foreach ( $articles_options as $key => $val ){ | |
print_r($key); // prints the post ID | |
print_r($val); // prints the post title | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment