You can simply add an if
statement around your foreach
loop to first check to see if there are posts available, and then output a message or loop through the posts.
global $post; // <- Don't forget this at the top of the page!
// ...
$terms = get_terms(
array(
'taxonomy' => 'location',
'hide_empty' => false // <- includes the term in query even if there are no posts associated with it
)
);
if ( $terms ) { // <- Don't forget the if wrapper
foreach ( $terms as $term ) {
$posts = get_posts( array( /* your parameters */ ) );
if ( $posts ) { // <- Checks if any posts are in the above query
foreach ( $posts as $post ) {
setup_postdata( $post ); // <- Populates the global $post variable with the looped post data, good practice
// ...
}
wp_reset_postdata(); // <- Resets the global $post variable to what it was, should be used in conjunction with setup_postdata()
} else {
// ... echo statement if no posts in term
}
}
} else {
// ... echo statement if no terms
}
The have_posts()
function is used in conjunction with WP_Query
, not get_posts()
like you’re using here. When using get_posts()
, use if ( $posts )
. Read more about WP_Query
here.
Generally not a bad idea to wrap any of your foreach
query loops with an if
statement, just in case there are no posts available. Then, you can output an appropriate message to the site instead of leaving it blank and leaving the user confused.