WordPress Passing Variables into Template Part

I recently found myself in the position where I needed to pass a variable into a template path within the WordPress loop. The reason for this was that the loop needed to show on the category pages: the first post as large thumb on left & title/text on right; the second post as full width featured image; the third and fourth as thumbs next to each other, then the subsequent posts as 3 in a row.

To achieve this I incremented a value within the loop and then loaded in the specific template based on the value that increment was. This all worked fine until I needed the third template with the thumbs next to each other, as within this template I needed to apply a CSS class based on whether the thumb was on the left or right. WordPress’s get_template_path() function is fine but it means you can’t access any of the variables from the template that exist within the loop.

Therefore you need to use:


include( locate_template( 'the-template-you-need.php' ) );

As this will then expose the variables to the template.

The full code block is as follows:


if($cat_id == 143) {
$i = 0;
if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
if(!is_paged()) {
if ($i == 0){
get_template_part( 'content', 'post-hero' );
}
if ($i == 1){
get_template_part( 'content', 'post-first-post' );
}
if ($i == 2 || $i == 3) {
// use include so it can pass vars into the tpl
include(locate_template('content-post-50-width.php'));
}
if($i >= 4 && $i < 12) { get_template_part( 'content', 'post-sub-cats' ); } } else { get_template_part( 'content', 'post-sub-cats' ); } $i++; endwhile; wp_reset_postdata(); endif; } else { if ( have_posts() ) : while ( have_posts() ) : the_post(); get_template_part( 'content', 'post-sub-cats' ); endwhile; wp_reset_postdata(); endif; }

Other points for clarity: it is only to show on the main blog category (ID 143 in this case), and it is only for the first postings display, hence the if(!is_paged()) condition.

Leave a Comment

Your email address will not be published.