Global page ID variable empty error
-
24-03-2021 - |
Question
I am creating theme and I have a need to create global variables within theme functions.php
file.
Currently I am doing it like this:
/**
* Setup globals
*/
global $nb_id, $nb_page;
$nb_id = get_the_ID();
// Prepare & set fallback
$globals_array = array(
'nb_id' => $nb_id,
'nb_page' => array(
'id' => $nb_id,
'end' => 'front',
'name' => 'home',
'type' => 'page'
)
);
// Set each value from globals array as global $var;
foreach ($globals_array as $name => $value) {
global $$name;
$$name = $value;
$_GLOBALS[$name] = $value;
// Set user view of page
if($name == 'nb_page'){
if(is_admin()) $$name['end'] = 'back';
$$name['name'] = $nb_pagenow;
// Determine if is page or single post
if(is_single()) $$name['type'] = 'single';
$_GLOBALS[$name] = $$name;
}
}
The issue is that I cannot retrieve front-end current page/post ID using get_the_ID()
, $wp_query->get_queried_object_id()
or even $wp->public_query_vars
with page_id
.
Currently all the scenarios return these values:
get_the_ID()
=null
$wp_query->get_queried_object_id()
=0
$wp->public_query_vars
="page_id" [34]=> string(5) "error"
Does anyone have any idea why I am having this issue? Am I doing something wrong? Maybe there is another way to call front-end page/post data within functions.php
!?
La solution
After some research and thanks to @Milo for pointing out about using hooks after wp
is set, I finnaly got it working. Indeed I had to call it as soon as wp
has queried and generated some post/page data;
This is my final solution, where I used add_action( 'template_redirect', 'nb_setup_globals' );
Here is the final code:
/**
* Setup globals
*/
global $nb_id, $nb_view, $nb_page;
function nb_setup_globals(){
global $post, $nb_id, $nb_view, $nb_page;
// Set default vars for globals
$nb_id = $post->ID;
$nb_view = 'front';
$nb_post_name = 'index';
$nb_post_type = 'post';
// Post type page
if(is_page()){
if(nb_get_template_slug()){
$nb_post_name = nb_get_template_slug();
}else{
$nb_post_name = 'page';
}
$nb_post_type = 'page';
}
// Post type post / custom post
if(is_single()){
$nb_post_name = $post->post_type;
}
// View
if(is_admin()) $nb_view = 'back';
// Before globals set default vars one last time
$globals_array = array(
'nb_page' => array(
'id' => $nb_id,
'name' => $nb_post_name,
'type' => $nb_post_type
)
);
/**
* Let the magin GLOBALS be registered
*/
foreach ($globals_array as $name => $value) {
global $$name;
$$name = $value;
}
}
add_action( 'template_redirect', 'nb_setup_globals' );
This also works in back-end (post/page edit etc.). Although haven't testet it fully.