0

I have the following:

$queryResponse = new \WP_Query(array(
    'post_type' => 'portfolio',
    'tax_query' => array(
        array(
            'taxonomy' => 'portfolio_date',
            'field'    => 'name',
            'term'     => $dateSelected
        )
    )
));

var_dump($queryResponse);

$dateSelected is '2015'.

I want: All posts from post type of portfolio with a custom taxonomy of portfolio_date (Actual name: Portfolio Date. This is what the user sees) that has the value of, in this case, 2015.

So if I create 6 posts under portfolio, with the portfolio date of 2015, I should get back 6 posts. Right now I get: 0 posts.

I do have 1 post under this post type with this taxonomy.

1

You have one or two issues here and possible future bugs that you might encounter

  • term in your tax_query should be terms

  • Be carefull with terms having dates as names and especially dates as slugs. This can cause issues and unexpected results if custom permalinks clash or if something falls into the template hierarchy for some reason.

  • Never use the name field in a tax_query. There is an issue with the sanitizing of the term name before the join clause is constucted for the SQL query in the WP_Tax_Query class. This is a known bug that will propably be there for many versions to come.

    I have explained the complete issue in this answer I have recently done, so feel free to go read the whole 9 yards. But in short, what basically happens is, WP_Tax_Query uses sanitize_title_for_query to sanitize the input from the name field in a tax_query. This function strips all whitespaces and special characters and also convert all capitals to lowercase. So a term name like My Term Name/2 gets converted to my-term_name2 which will fail as that term name does not exist.

    In short, as precaution, do not use the name field in a tax_query, rather use term_id or slug. If you do not know these values, then use get_term_by() to get the term ID or slug from the name and then pass that to the tax_query

  • You should also make sure that you can query posts from your custom taxonomy and custom post type publically. Make sure that have the correct values set when you register the post type and taxonomy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.