Categories
WordPress

How To Wrap WordPress’ Loop Posts Without Changing Theme Template

So here’s the task at hand. Let’s say you want to wrap your posts on the main loop:

<div class="wrapper">
  <!-- START WRAP HERE -->
  <article class="post-1">
  </article>
  <article class="post-2">
  </article>
  <article class="post-3">
  </article>
  <!-- END WRAP HERE -->
</div>

which is generated by this:

<div class="wrapper">
  <?php while ( have_posts() ) : ?>
    <?php the_post(); ?>
    <?php get_template_part( 
      'content', 
      get_post_format() 
    ); ?>
  <?php endwhile; ?>
</div>

But you can’t modify the theme template because it won’t be feasible; What are your option? loop_start and loop_end.

loop_start

You can check out about loop_start at documentation here. I personally found it out while roaming around core code at https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-query.php#L3278.

loop_end

Similar to loop_start, read about loop_end documentation here. Again, i found it much easier to understand the context by seeing it on core code: https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-query.php#L3305

Example / Putting it together

To use it, you can do something like this at the theme’s functions.php:

function fr_wrap_main_loop_start() {
  echo '<div class="custom-posts-wrap">';
}
add_action( 'loop_start', 'fr_wrap_main_loop_start' );

function fr_wrap_main_loop_end() {
  echo '</div><!--- .custom-posts-wrap -->';
}
add_action( 'loop_end', 'fr_wrap_main_loop_end' );

You’ll get something like:

<div class="wrapper">
  <div class="custom-posts-wrap">
    <article class="post-1">
    </article>
    <article class="post-2">
    </article>
    <article class="post-3">
    </article>
  </div><!--- .custom-posts-wrap -->
</div>

Pretty neat 👌

***

Photo by DiEtte Henderson on Unsplash