Pass a variable to get_template_part

In category-about.php I have

<?php
/**
 * The template for displaying the posts in the About category
 *
 */
?>
<!-- category-about.php -->
<?php get_header(); ?>

<?php
  $args = array(
    'post_type' => 'post',
    'category_name' => 'about',
  ); ?>

  <?php  
    // important bit
    set_query_var( 'query_category', $args );

    get_template_part('template-parts/posts', 'loop');
   ?>   
<?php get_footer(); ?>

and in template file posts-loops.php I now have

<!-- posts-loop.php -->
    <?php
    // important bit
    $args = get_query_var('query_category');

    $cat_name = $args['category_name'];
    $query = new WP_Query( $args );
    if($query->have_posts()) : ?>
      <section id="<?php echo $cat_name ?>-section">
      <h1 class="<?php echo $cat_name ?>-section-title">
        <strong><?php echo ucfirst($cat_name) ?> Section</strong>
      </h1><?php
      while($query->have_posts()) : $query->the_post(); ?>
        <strong><?php the_title(); ?></strong>
          <div <?php post_class() ?> >
            <?php the_content(); ?>
          </div> <?php
          endwhile; ?>
    </section> <?php
    endif;
    wp_reset_query();

and it works.

Reference:
http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/#comment-110459
https://wordpress.stackexchange.com/a/176807/77054

Leave a Comment