Function that saves new WP Query to array for use on single.php

Is it possible to run a function that always queries for a related post and saves that array to a variable in WordPress?

if ( !function_exists( 'the_query_vars' ) ) {
function the_query_vars() {
  global $post;

  if ($post->post_status == 'publish') {  

    $args = array(
    'post_type' => 'sponsor'
    ,'posts_per_page' => 1
    ,'post_belongs' => $post->ID
    ,'post_status' => 'publish'
    ,'suppress_filters' => false
    );

    $sponsor_query = new WP_Query($args);
    return $the_query; 
  }
 add_action( 'init', 'the_sponsor_vars' );
} }

Then I just wanted to use the $the_query “object?” and use it as if I had done a regular new WP_Query() from within the template file? Calling it out with familiar hook like:

Read More

echo $the_query->post_title

Tried the simplest thing first:
<?php print_r($the_query);?>

Been unsuccessful in returning the array of variables.

I considered that it was because the variable wasn’t globally set, but I thought the advantage of the return command was to essentially store the results for use if the function is activated.

Related posts

1 comment

  1. The function returns the Variable and not make it global.
    If you want to access the result you have to assign the result of the function to a variable.

    if (!function_exists('the_query_vars')) {
        function the_query_vars()
        {
            global $post;
    
            if ($post->post_status == 'publish') {
    
                $args = array(
                    'post_type' => 'sponsor'
                , 'posts_per_page' => 1
                , 'post_belongs' => $post->ID
                , 'post_status' => 'publish'
                , 'suppress_filters' => false
                );
    
                $sponsor_query = new WP_Query($args);
                return $sponsor_query;
            }
            add_action('init', 'the_sponsor_vars');
        }
    }
    

    and where you want to use the result of the function:

    $the_query = the_query_vars();
    

Comments are closed.