static array on functions.php

In functions.php, I want to access the DB once to get an ACF object, and then “save” it locally to prevent further requests to the DB.

I thought of first calling the following function in the “init’ hook.

Then, supposedly, when I call it on later hooks the $current_store var is already set because of the use of the “static” keyword, and the function will stop on the first “if” – returning the already saved static var.

It doesn’t work – when accessing the function on later hooks ‘isset($current_store)’ returns false.

What am I doing wrong?

function get_current_store()
{
if (isset($current_store)) {
return $current_store;
}

$store_url_parts = explode(‘.’, $_SERVER[‘HTTP_HOST’]);
$store_subdomain = $store_url_parts[0];

$store_url_parts_reversed = array_reverse($store_url_parts);

if (in_array(“il”, $store_url_parts_reversed)) {
$domain = $store_url_parts_reversed[2];
} else {
$domain = $store_url_parts_reversed[2];
}

if ($store_subdomain == $domain) {
$current_store = ‘main’;

return $current_store;
}

if ($stores_page = get_page_by_title(‘Stores’, OBJECT, ‘option’)) {
$stores_page_id = $stores_page->ID;

if (function_exists(‘have_rows’)) {
if (have_rows(‘stores’, $stores_page_id)) {
$store_url_parts = get_store_url_parts();
$store_subdomain = $store_url_parts[0];
$stores = array();

while (have_rows(‘stores’, $stores_page_id)) {
the_row();

$store = get_row(true);

$stores[] = $store;
}

$subdomains = array_column($stores, ‘store_subdomain’);

$current_store_id = array_search($store_subdomain, $subdomains);

static $current_store = array();

if ($current_store_id !== false) {
$current_store = $stores[$current_store_id];
} else {
$current_store = false;
}

return $current_store;
}
}
}

}

Read more here:: static array on functions.php

Leave a Reply

Your email address will not be published. Required fields are marked *