0

I have a function.php file in my plugin I am making and I want a function that gets all data from a table in the DB then stores it in a $data array. My problem is when I call the function outside the functions file the array is null, if I dump the data array out inside the function and then call the function the data is present so I know the query is successful. Here is my code:

functions.php

    function getCategories() {

    $data = array();

    global $wpdb;
    $data = $wpdb->get_results("SELECT * FROM `metal_work_categories` WHERE 1", ARRAY_N);

    }

index.php

include('functions.php');

getCategories();
var_dump($data);

I also tried initializing the data array in the index.php file and passing it to the function, just a wild stab in the dark really, to no avail:

$data = array();
getCategories($data);
var_dump($data);

1 Answer 1

2

That's how variable scope works. You need to return the data you want from the function, and assign it to a variable.

function getCategories() {
   global $wpdb;
   return $wpdb->get_results("SELECT * FROM `metal_work_categories` WHERE 1", ARRAY_N);
}

$data = getCategories();

PS: Next up, stop using global!

Sign up to request clarification or add additional context in comments.

1 Comment

why stop using global?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.