Last active
August 9, 2019 03:17
-
-
Save gmazzap/c3e29d8999ec1b722dd17b87dddac62e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace gmazzap; | |
/** | |
* @param callable $looper Callback that receives post object, post index and current WP_Query. | |
* It is possible to use any template tags inside the callback. | |
* @param array $args Array of WP_Query arguments. Optional, when not provided, main query will be used. | |
*/ | |
function loop(callable $looper, array $args = null) { | |
$query = $args === null ? $GLOBALS['wp_query'] : new \WP_Query($args); | |
array_walk($query->posts, function(\WP_Post $post, int $index, \WP_Query $wp_query) use ($looper) { | |
$GLOBALS['post'] = $post; | |
$wp_query->the_post(); | |
$looper($post, $index, $wp_query); | |
$wp_query->have_posts(); // this will fire 'loop_end' when needed | |
}, $query); | |
$args === null or wp_reset_postdata(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example with main query:
Example with custom query: