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:
$hasposts = get_posts('post_type=sc-events&category=40');
if( !empty ( $hasposts ) ) {
..// show the drop down menu
}
or
$query = new WP_Query(array(
'post_type' => 'sc-events',
'category' => 40
));
if( $query->have_posts() ){
echo 'we have posts';
} else {
echo 'no posts found';
}
While this will work, there’s an alternative inspired by your own answer that uses the category slug rather than its ID:
$term = get_term_by('name', 'whatever category 40 is called', 'category');
if($term != false ){
if($term->count > 0 ){
// we have posts
}
}