I’m building a navigation, outside of the main loop, that includes drop downs. I have a custom post type called ‘Events’, that has its own categories. I would like there to be a drop down if there are posts within that custom post type and category, but I’m not sure what functions I should be using to determine this…
I have…
$hasposts = get_posts('post_type=Events&category=40');
if($hasposts) {
..// show the drop down menu
}
Should I even be using get_posts()
? Everything I am getting returned has an empty array, but I know that some of those categories include posts…
Many thanks, WA.
It all boils down to WP_Query in the end even if you use get_posts, here’s my modified version:
or
While this will work, there’s an alternative inspired by your own answer that uses the category slug rather than its ID:
If you want to have an array with all the terms inside your custom taxonomy, with the additional condition that they contain at least on post, this is the function you’re looking for:
This will retrieve information regarding the terms, not the posts themselves. The only thing you know about posts in this scenario is that they exist within those terms, nothing else. If the dropdown menus will display some kind of information regarding the posts, maybe you’ll need something other than the above. Otherwise, get_terms is the function you’re looking for.
I was able to perform this conditional check through the following code –
There is no reason to return the full get_posts object you can keep things better optimized by using the fields parameter to return the ID’s only