https://github.com/wp-forge/wp-loop
A generator function that makes working with the WordPress loop a dream.
https://github.com/wp-forge/wp-loop
wordpress-library
Last synced: about 1 year ago
JSON representation
A generator function that makes working with the WordPress loop a dream.
- Host: GitHub
- URL: https://github.com/wp-forge/wp-loop
- Owner: wp-forge
- License: gpl-2.0
- Created: 2020-07-09T02:52:26.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2020-07-09T02:56:41.000Z (almost 6 years ago)
- Last Synced: 2025-03-25T03:11:13.216Z (over 1 year ago)
- Topics: wordpress-library
- Language: PHP
- Homepage:
- Size: 9.77 KB
- Stars: 10
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# WordPress Loop
A generator function that makes working with the WordPress loop a dream.
**When will this land in WordPress core?**
At the moment, that is unclear. However, you can follow the progress of this [trac ticket](https://core.trac.wordpress.org/ticket/48193).
## Installation
- Run `composer require wp-forge/wp-loop`
- Make sure you require the `vendor/autoload.php` file in your project.
## Usage
Here are a few examples of how to use the `wp_loop()` function:
### With the Global `WP_Query` Instance
```php
'post' ] );
foreach ( wp_loop( $query ) as $post ) {
?>
'post' ] );
$posts = $query->posts;
foreach ( wp_loop( $posts ) as $post ) {
?>
'post',
'fields' => 'ids',
] );
$post_ids = $query->posts;
foreach ( wp_loop( $post_ids ) as $post ) {
?>
'post' ] );
$iterator = new ArrayIterator( $query->posts );
foreach ( wp_loop( $iterator ) as $post ) {
?>
have_posts() ) {
// For custom query approach
}
if( ! empty( $posts ) ) {
// For post or post ID approach
}
if( $iterator->valid() ) {
// For iterator approach
}
```
The `wp_loop()` function goes one step further than the standard WordPress loop does and automatically sets and restores the global `$post` object for each iteration.
For more details, read this blog post on [Creating a Better WordPress Loop](https://wpscholar.com/blog/creating-better-wordpress-loop/). The current implementation is a bit different, but the reasoning is laid out quite well.