Skip to content

Instantly share code, notes, and snippets.

@gmazzap
Last active August 9, 2019 03:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmazzap/c3e29d8999ec1b722dd17b87dddac62e to your computer and use it in GitHub Desktop.
Save gmazzap/c3e29d8999ec1b722dd17b87dddac62e to your computer and use it in GitHub Desktop.
<?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();
}
@gmazzap
Copy link
Author

gmazzap commented May 22, 2017

Example with main query:

gmazzap\loop(function(\WP_Post $post, int $post_index, \WP_Query $wp_query) {
    ?>
	<div id="post-<?= $post->ID ?>" <?php post_class($post_index %2 === 0 ? 'even' : 'odd', $post->ID) ?>>
		<h2 class="title"><?php the_title() ?></h2>
		<div><?php the_content() ?></div>
	</div>
    <?php
});

Example with custom query:

gmazzap\loop(function(\WP_Post $post, int $post_index, \WP_Query $wp_query) {
    ?>
	<div id="post-<?= $post->ID ?>" <?php post_class($post_index %2 === 0 ? 'even' : 'odd', $post->ID) ?>>
		<h2 class="title"><?php the_title() ?></h2>
		<div><?php the_content() ?></div>
	</div>
    <?php
}, ['post_type' => 'product', 'posts_per_page' => 10]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment