I was recently answering a question on WordPress StackExchange and the question of appropriate hooks came up when suggesting where to hook on your styles or scripts when you’re needing to check conditional tags, those such is_page(), is_category, and so on..
http://wordpress.stackexchange.com/questions/8260/loading-scripts-on-specific-pages/
It was my impression, that both wp_print_scripts and wp_print_styles were front facing page actions that occur at a time equivalent to their admin counterparts and a query was raised by Rarst whether this is an appropriate place for enqueues..
The codex also suggests init as appropriate for enqueues.
Warning: You can only use conditional query tags on or after the init action hook in WordPress. For themes, this means the conditional tag will never work properly if you are using it in the body of functions.php, i.e. outside of a function.
I decided to write a PHP class as an example to get the results of hooking onto different actions because i was sure init was too early.
class conditional_tags_check {
private $results = array();
public function __construct() {
add_action( 'wp_head', array( $this, 'conditional_check' ) );
add_action( 'template_redirect', array( $this, 'conditional_check' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'conditional_check' ) );
add_action( 'wp_print_styles', array( $this, 'conditional_check' ) );
add_action( 'wp', array( $this, 'conditional_check' ) );
add_action( 'init', array( $this, 'conditional_check' ) );
add_action( 'wp_print_scripts', array( $this, 'conditional_check' ) );
add_action( 'wp_footer', array( $this, 'output' ) );
}
public function conditional_check() {
$action = debug_backtrace();
$action = $action[2]['args'][0];
$this->results[] = "$action :" . ( is_page() ? 'yes' : 'no' );
}
public function output() {
echo implode( "\n<br />", $this->results );
}
}
$conditional_tags_check = new conditional_tags_check;
I’ve purposely put the add action calls into a random order so you can see the natural order of the actions appear in the results(naturally the action occuring first will be the first result, and so on..).
The results for me came out as.
init :no
wp :yes
template_redirect :yes
wp_enqueue_scripts :yes
wp_print_styles :yes
wp_print_scripts :yes
wp_head :yes
Init is the only action that fails the test, and shows “no”, where as all others appear to run late enough to determine the request is for a page(i was of course viewing a page). The above conditional tag could be replaced by any other and replicated to show that under each condition init fires too early to determine the kind of request(page, category, tag, single, etc..).
For reference the actions shown above fire in this order.
- init
- wp
- template_redirect
- wp_print_styles
- wp_print_scripts
- wp_enqueue_scripts
- wp_head
Can anybody see any problems with the test code or disagree? Drop me a comment..