PHP code example of jascha030 / wp-post-iterator

1. Go to this page and download the library: Download jascha030/wp-post-iterator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jascha030 / wp-post-iterator example snippets




/**
 * Create instance from any arguments you would pass to a WP_Query.
 */
public static function fromQueryArgs(array $args, bool $keyByPostId = false): PostCollection

/**
 * Create instance from an existing WP_Query instance.
 */
public static function fromQuery(WP_Query $query, bool $keyByPostId = false): PostCollection

/**
 * Create instance inside a globally accessible post loop.
 */
public static function fromLoop(bool $keyByPostId = false): PostCollection



// Require Composer's autoloader
   'posts_per_page' => -1,
    'post_status' => 'publish'
];

// Create from arguments you would pass to a WP_Query instance (Recommended).
$fromArgs = \Jascha030\WpPostIterator\PostCollection::fromQueryArgs($args);

// Or from an existing instance.
$query = new WP_Query($args);
$fromQuery = \Jascha030\WpPostIterator\PostCollection::fromQuery($query);



$collection = \Jascha030\WpPostIterator\PostCollection::fromQueryArgs($args);

foreach($collection as $post) {
    echo "<h1>{$post->post_title}</h1>";
    
    echo "<p>{$post->post_content}</p>";
}




/**
 * Simple implementation, extends WP_Query and uses its methods to implement the Iterator interface.
 */
class PostIterator extends \WP_Query implements \Iterator
{
    public function __construct($query = '')

    /**
     * Tells the `key` method whether we should return the post ID when called.
     * If so, this doesn't necessarily mean the posts would be ordered ID.
     */
    final public function keyByPostId(bool $enabled = true): \Iterator

    public function current(): ?\WP_Post

    public function next()

    public function key(): ?int

    public function valid(): bool

    public function rewind(): void
}



class PostIteratorAdapter implements \Iterator
{
    use PostIteratorTrait;

    public function __construct(WP_Query $query)

    /**
     * Provide a WP_Query object to defer our calls to.
     */
    private function getQuery(): WP_Query
    
    /**
     * Tells the `key` method whether we should return the post ID when called.
     * If so, this doesn't necessarily mean the posts would be ordered ID.
     */
    private function keyedByPostIds(): bool

    final public function keyByPostId(bool $enabled = true): \Iterator
}


/**
 * Provide a WP_Query object to defer our calls to.
 */
abstract private function getQuery(): WP_Query;

/**
 * Tells the `key` method whether we should return the post ID when called.
 * If so, this doesn't necessarily mean the posts would be ordered ID.
 */
abstract private function keyedByPostIds(): bool;