How do you run code on a specific page without missing the init hook?

The earliest that functions such as get_permalink or is_page are available is parse_query (afaik). Then I thought, ok, clearly, I can’t say if( is_page('myPage') ) { add_action( 'init'... // because is_page will always resolve to false.

So then I thought, well, how about wrapping parse_query inside init like so:

add_action( 'init', function() {     add_action( 'parse_query', function() use() {         if( is_page( 'myPage' ) ) { //     }, 10 ); }, 10 ); 

Well, that still does nothing. The code works, but hooking into init there doesn’t really work. My goal here is to make use of items that need to launch/are available on init:10. So, I said, ok, just pass them, right?

add_action( 'init', function() {   $  something_i_need_from_init_10 = //do something.   add_action( 'parse_query', function() use( $  something_i_need_from_init_10 )   // } 

Which works, now, there are two cases that you’ll use this for:

  1. Getting something. If it’s available on init:10, isn’t it available on parse_query since parse_query come after? Sure, for most things, but remember that WP core itself gets rid of certain get_post_* functionality once it hits certain actions. Perhaps you have a service container that works well with WP and a service is only available on init:10.
  2. Doing something. Perhaps something needs to fire here. If so, this still works.

But all of this is clunky to write.

Is there no way to tell WP to run code on init, on a certain page only? Just looking at the link won’t do. There are rewrite rules, link formats and so on that one has to take care of and that probably don’t load until later on.

Ultimately, it’d be nice if all I had to write was:

add_action( 'init', function() {   if( is_page( 'myPage' ) ) {     //do stuff   } } 

What can one do when trying to design this way?


I don’t know how to figure it myself, but perhaps pipelining this process through the page.php / single.php pages will work. I assume WP has to figure out very early on what page, with what template it has to serve for any given link, for which it calls these 2 (usually).