Using a variable from one hook in another hook.

I have two functions that hook into two areas of my frontpage. Each one has a wp_query to display one post at random. I would like the second function to avoid selecting the post from the first function.

I've tried to include the post ID from the first function in a variable: $primaryID = the_post_ID();. And then exclude it from the wp_query in the second function: 'post__not_in' => array($primaryID);. I understand that variables are contained within their function, and so I would need to put it in a global variable. Given that this is bad practice how would you do it better? Below is my current code.

add_action( 'LocationOne', 'postPrimary', 10 );

function postPrimary() {

           if ( is_front_page() ) {

           // args
           $wpQuery1 = array(
                       'posts_per_page' => 1,
                       'orderby' => 'rand'
           );

           // query
           $wpQuery1 = new WP_Query( $expiry );?>

           <?php if( $expiryQuery -> have_posts() ) :

                      while( $expiryQuery -> have_posts() ) : $expiryQuery -> the_post(); 
                      global $post;

                      $primaryID = get_the_ID(); 

                                 echo 'POST CONTENT';

                      endwhile; 

           wp_reset_postdata(); ?>

add_action( 'LocationTwo', 'postSecondary', 11 );

function postSecondary() {

           if ( is_front_page() ) {

           // args
           $wpQuery2 = array(
                      'posts_per_page' => 1,
                      'orderby'  => 'rand',
                      'post__not_in' => array( $primaryID )
           );

           // query
           $wpQuery2 = new WP_Query( $expiry );
           $primaryID = get_the_ID(); ?>

           <?php if( $wpQuery2 -> have_posts() ) :

                      while( $wpQuery2 -> have_posts() ) : $wpQuery2 -> the_post(); 
                      global $post;

                                 echo 'POST CONTENT';

                      endwhile; 

           wp_reset_postdata(); ?>

wpQuery2 is not excluding the post because the variable is in a different function. I've also tried to experiment with recalling the $primaryID variable from the postPrimary function before the $args in $wpQuery2, but I could not get it to work at all. I've also tried moving the add_action into the wp_query but that doesn't work either. This has been baffling me for awhile and I'd love some direction.

A global variable of some kind is likely your best bet in PHP, something like this:

https://stackoverflow.com/questions/18517705/pass-php-variable-created-in-one-function-to-another

Cheers Eric. Was hoping to avoid globals, but I think that might have to be the way forward. Thanks!

Sure thing. 🙂

Log in to reply