WordPress.org

Make WordPress Core

Opened 3 weeks ago

Last modified 3 weeks ago

#48193 new enhancement

Improve the WordPress loop

Reported by: wpscholar Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Query Keywords: has-patch dev-feedback needs-testing
Focuses: Cc:
PR Number:

Description

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 https://wpscholar.com/blog/creating-better-wordpress-loop/

Attachments (1)

trac-48193-wp-loop.diff (1.2 KB) - added by wpscholar 3 weeks ago.

Download all attachments as: .zip

Change History (5)

#1 @wpscholar
3 weeks ago

  • Version trunk deleted

#2 @knutsp
3 weeks 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
3 weeks 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
3 weeks 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.

Note: See TracTickets for help on using tickets.