Opened 4 years ago
Last modified 3 years ago
#48193 new enhancement
Improve the WordPress loop
Reported by: |
|
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: |
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 (2)
Change History (9)
#3
@
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
@
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
@
3 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
This ticket was mentioned in PR #150 on WordPress/wordpress-develop by wpscholar.
3 years ago
#7
Pull request for WordPress trac ticket #48193 (https://core.trac.wordpress.org/ticket/48193)
Thank you for the suggestion! Now, that's very interesting.
Just needs testing of every scenario, including performance compared to the classic loop setup.