WordPress.org

Make WordPress Core

Opened 3 months ago

Closed 3 months ago

Last modified 3 months ago

#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 @boonebgorges
3 months ago

  • Milestone Awaiting Review deleted
  • Resolution set to invalid
  • Status changed from new to closed

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 a WP_Query or tax_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.

#2 @SergeyBiryukov
3 months ago

  • Component changed from General to Taxonomy
  • Focuses performance removed

#3 @Digital Noises
3 months 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?)

Note: See TracTickets for help on using tickets.