Get a variable from one wordpress template file to another

I have a template file (trendingPosts.php) for showing 2 latest posts with the tag ‘trending’. In the while loop for displaying these 2 posts, I take their ID’s in an array so I can exclude them from the main wordpress loop later:

<div id="trendingWrap" class="clearfix">

<?php
$trending = new WP_Query();
$trending->query("showposts=2&tag=trending");
while($trending->have_posts()) : $trending->the_post();
$wp_query->in_the_loop = true;
$currentTrending[] = $post->ID;
?>

    <div class="trendingStory">
        <h2 class="trendingTitle"><a href="<?php the_permalink(); ?>" alt="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
    </div><!-- end trendingStory -->

<?php endwhile; ?>

</div><!-- end trendingWrap -->

The problem is that I have an index.php in which I include the loop.php via get_template_part( 'loop', 'index' ); and I am unable to get the $currentTrending[] array that I made in trendingPosts.php. I need to get that array in my loop.php

Read More

Moreover, in my loop.php, I am excluding the 2 posts in the following way.

if(have_posts()): while(have_posts()) : the_post(); 
    if( $post->ID == $currentTrending[0] || $post->ID == $currentTrending[1] ) continue;

Is this the right way to exclude posts? if anybody has a better way of doing this whole thing. Please let me know. Of course nothing works until I manage to get that array in loop.php so that is the main issue.

Thanks! I appreciate all the help.

Related posts

Leave a Reply

2 comments

  1. You can easily create variables that you can access everywhere by using the $GLOBALS superglobal array.

    Once set

    $GLOBALS['mytheme_thisismyvar'] = 22;
    

    You can then access it everwhere in the other templates:

    $myvar = $GLOBALS['mytheme_thisismyvar'];
    

    And use it where it suits. This works with sub-templates regardless how they get loaded.

    Because the whole program shares this superglobal array, take care that you do not overwrite existing values.

  2. Try moving your current trending code to the theme’s functions.php, so that you can call on it whenever you need.

    function getCurrentTrending() {
      $trending = new WP_Query();
      $trending->query("showposts=2&tag=trending");
      while($trending->have_posts()) : $trending->the_post();
        $wp_query->in_the_loop = true;
        $currentTrending[] = $post->ID;
      endwhile;
      return $currentTrending;
    }
    

    You can then fetch that array from any template file:

    $currentTrending = getCurrentTrending();
    

    Hope that helps.