#41708 closed defect (bug) (invalid)
tax_query not (instantly) available from functions.php
Reported by: | Digital Noises | Owned by: | |
---|---|---|---|
Milestone: | Priority: | normal | |
Severity: | normal | Version: | 4.8.1 |
Component: | Taxonomy | Keywords: | |
Focuses: | Cc: |
Description
I created a tax_query of a custom post type from within a file that I referenced in functions.php
I figured out that I could query all of my custom posts by using: (so I had my positive)
<?php $args = array('post_type' => 'mycpt');
I assumed it should be easy to specify my quey with a tax_query
<?php 'tax_query' => array( array( 'taxonomy' => "mytax", 'field'=>'slug', 'terms'=> array('mytaxterm') ) )
Unfortunately this returns no result at all from within functions BUT from within i.e. header.php
My workaround to retrieve all needed values from all those posts was - calling it via a hook from within functions.php
(might be a dumb way?!)
I added:
<?php add_action( 'wp_head','doMyTaxQuery' );
And did all I needed to do inside the function »doMyTaxQuery«.
PS: I figured that I could not use »get_terms« from my query inside functions.php either.
Change History (3)
#1
@
7 years ago
- Milestone Awaiting Review deleted
- Resolution set to invalid
- Status changed from new to closed
#3
@
7 years ago
Thank you @boonebgorges - wouldn't it make sense to add something like »availalable after init« to the WP_query documentation on https://codex.wordpress.org/Class_Reference/WP_Query then? (Or do I simply not see/find it?)
Hi @Digital Noises - Thanks for the ticket, and welcome to WordPress Trac.
Taxonomies and post types cannot be reliably referenced until after the
init
hook, which is when WordPress and most plugins register them. If you need to perform some logic on every pageload that requires aWP_Query
ortax_query
,wp_loaded
is the first recommended place to do it.wp_head
runs much later, and will work fine as long as you don't need to perform a redirect or any other actions that'd result in "headers already sent" messages; at this point, WP has already begun to build the HTML page.