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.