Make WordPress Core

Opened 4 years ago

Last modified 4 years ago

#48193 new enhancement

Improve the WordPress loop

Reported by: wpscholar's profile wpscholar Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Query Keywords: has-patch dev-feedback needs-testing has-unit-tests 2nd-opinion
Focuses: Cc:


Currently, there are a number of ways that the "loop" can be handled in WordPress. Each depends on whether you are using the WP_Query global, a custom WP_Query instance, or an array of posts.

I propose that we add a PHP 5.6+ compatible generator function called wp_loop() that will simplify all of these use cases into a single, more modern approach. See

Attachments (2)

trac-48193-wp-loop.diff (1.2 KB) - added by wpscholar 4 years ago.
trac-48193-wp-loop-with-tests.diff (356.2 KB) - added by wpscholar 4 years ago.

Download all attachments as: .zip

Change History (9)

#1 @wpscholar
4 years ago

  • Version trunk deleted

#2 @knutsp
4 years ago

Thank you for the suggestion! Now, that's very interesting.

Just needs testing of every scenario, including performance compared to the classic loop setup.

#3 @mukesh27
4 years ago

@wpscholar Can you please add doc for global $post variable in the patch trac-48193-wp-loop.diff?

* @global WP_Post $post Global post object.

#4 @ayeshrajans
4 years ago

  • Keywords needs-testing added

This indeed looks interesting! Do you have any use cases in existing core loops so we can benchmark for time/memory?

Speaking from a clean code perspective, using global variables in new function seems a bit off, where we could create a function with proper typing and be more strict, and hand over the responsibility of passing correct \WP_Query instance to the caller. This will make writing tests quite easy too.

In the original patch, there is a line if ( ! is_array( $posts ) ) {. May be we can use is_iterable here? WordPress has a polyfill for this PHP 7.1 function, and this will allow callers to pass Traversable instances too, which the foreach block that proceeds it will happily accept. Because we are talking about using generators over array, I think it's safe to assume the callers would have Traversable objects instead of arrays.

#5 @wpscholar
4 years ago

  • Keywords has-unit-tests added

Just added some unit tests and made a few changes to the function. It now supports the passing of an iterator, not just an array or query instance. The doc was updated to include an @global for the $post object

#6 @wpscholar
4 years ago

  • Keywords 2nd-opinion added

This ticket was mentioned in PR #150 on WordPress/wordpress-develop by wpscholar.

4 years ago

Pull request for WordPress trac ticket #48193 (

Note: See TracTickets for help on using tickets.