I’m facing an issue with the is_tax() function.
I’m a class method that fetches a specific custom post types. These custom post types have taxonomy related custom fields (among other custom fields).
If in these custom fields I find, for instance, a value for the category term “discografia”, I want my method to return this custom post type if I’m currently seeing the archive page /category/discografia.
This is an excerpt of my code:
// The Query
/** @var $query WP_Query */
$query = new WP_Query($query_args);
$results = false;
// The Loop
if ($query->have_posts()) {
if (!is_home() && !is_front_page()) {
$posts = $query->get_posts();
foreach ($posts as $post) {
$add = false;
//ServiceBoxes::getBox returns the $post object as Array_A
//and adds a new key "meta" with the custom fields I want to use
$box = ServiceBoxes::getBox($post->ID);
if (is_archive()) {
if (isset($box['meta'][self::$prefix]['taxonomies'])) {
foreach ($box['meta'][self::$prefix]['taxonomies'] as $tax => $terms) {
if ($terms) {
if (is_tax($tax, $terms)) {
$add = true;
}
}
}
}
}
if ($add) $results[] = $box;
}
} else {
$results = $query->get_posts();
}
return $results;
}
return false;
Some clarification about what happens here:
1. $box[‘meta’][self::$prefix][‘taxonomies’] actually returns an array with “category” as key and an array of terms (including “discografia”)
2. The url /category/discografia/ actually returns a series of posts
3. is_tax($tax, $terms) returns false
4. Also is_tax(‘category’, ‘discografia’) returns false
I suspect that the instance of WP_Query inside my method is overriding the global query, but I don’t see why: it’s a new instance, there is no reason for is_tax() to get confused.
However, with some step-by-step debugging here’s what happens in is_tax when called as is_tax('category', array('discografia'))
:
$wp_query->is_tax( $taxonomy, $term )
is called byis_tax()
- in
$wp_query->is_tax()
,if ( !$this->is_tax )
returns false
I’ve been able to reach this point: after that, I don’t know what else I can do to understand why the is_tax property is not set as expected.
With the debugger on and some variables in the watch list, here is what I can see when calling “/category/discografia/” (an archive page that, I repeat, returns posts): http://www.evernote.com/shard/s6/sh/88f05447-edff-40c7-9670-902f0a92bc62/b50a28d39c9e55c7d404f912175975a4
If you take a look at this part of the
WP_Query
class:then it looks like on category archive pages where
is_category
givestrue
thenis_tax
isfalse
.So it looks like you will have to use a mix of
is_category
andis_tax
😉Update:
Take a look at this ticket:
http://core.trac.wordpress.org/ticket/18636
It’s status is currently closed with wontfix!