How to widen the scope of a variable PHP?

I’m running a query in WordPress and need to re-use the $my_query_results variable later on in my script.

function init() {

    $args = array(
        'post_type' => 'post'
    );
    $my_query_results = new WP_Query( $args );
}

Read More
function process() {
    // I need to process $my_query_results here.
}
add_action( 'wp_ajax_myaction', 'process' );

I don’t want to re-run the query inside process(). How can I make $my_query_results available to the process() function?

Background info: The process() function handles data sent via an AJAX request. After processing, it sends a response to the browser. For example: echo json_encode( $response )

Related posts

Leave a Reply

3 comments

  1. If these functions are present in the same class you could assign it to a class property:

    class Class
    {
        public $my_query_results;
    
        function init(){
            $args = array(
                'post_type' => 'post'
            );
            $this->my_query_results = new WP_Query( $args );
        }
        function process() {
            // access $this->my_query_results
        }
    }
    
  2. You could pass the variable as a param

    function init(&$my_query_results) {
    
        $args = array(
            'post_type' => 'post'
        );
        $my_query_results = new WP_Query( $args );
    }
    
    function process(&$my_query_results) {
        // I need to process $my_query_results here.
    }
    

    usage

    init($my_query_results);
    process($my_query_results);
    
  3. or You can simply do global variable:

    $my_query_results = null;
    function init() {
    
    $args = array(
        'post_type' => 'post'
    );
    $my_query_results = new WP_Query( $args );
    

    }