Specifically, is it valid to run a new WP_Query()
during the plugins_loaded
action?
3 Answers
As @Milo pointed out in the comments above, custom post types and taxonomies are registered on init
, so this would seem to be the earliest hook available that is guaranteed to work for all content.
-
As my last comment is hidden below the fold above, I'll just add that in practice it is a bit confusing; I was able to both insert and retrieve custom-post-type posts on the
plugins_loaded
action -init
just seems safer.– EpFCommented Feb 4, 2016 at 12:12 -
wp_query has very little to do with CPT registration as it runs on the DB. The results of the query might not be very useful but that depends how you want to use them. Commented Feb 4, 2016 at 12:21
-
1@MarkKaplun will a tax query succeed if it's not a registered taxonomy returned by
get_taxonomies
? I've noticed that invalid post types or taxonomies result in an impossible SQL condition, are those values not validated against registered types?– MiloCommented Feb 4, 2016 at 17:24 -
1@Milo, not sure how taxonomies work, but wp_query should be a relatively easy query on the posts table and if the post_type in the table is "X" then querying for it should return it even if it is not registered as a post type. How will that impact any code after the query itself I guess depends on what you do with the results. Commented Feb 4, 2016 at 17:45
You should not use any hook before wp_loaded
unless it performs some initialization, or required for user authentication, therefor the earliest is wp_loaded
This is template_redirect
Here : https://www.rarst.net/images/wordpress_core_load.png
add_action('template_redirect', 'yourFunction');
WP_Query
can run in almost any scenario on any hook depending on what you need to do. You'll need to add some context here, specially the code and errorplugins_loaded
and is only available oninit
which runs later thanplugins_loaded
init
, I'd guess that you can't reliably do any querying until after that, but maybe core types would work earlier.plugins_loaded
. Still, after looking at this: wordpress.stackexchange.com/questions/155108/… I tried dumping$wp_post_types
and it only had core items. I find this very confusing, but I'm going to continue on the basis thatinit
is the earliest completely reliable action to use.