get_terms
returning empty array even though there are many terms it has?
Creating custom taxonomies are common when we design complex web applications. I hear your mind voice, We create a custom taxonomy for simple applications as well. Yeah, that’s right. Creating custom taxonomy has no restrictions. It’s purely based on the requirement of the application.
So, we created our own taxonomy and added many terms to it. It shows all terms on the UI perfectly. But when querying on the code, with the get_terms
function, it always returns empty array right?
get_terms( 'my_custom_taxonomy' );
This is not a WordPress bug, but an expected output. Yes it is.
If you closely look at the supported arguments in the WP_Term_Query class, you can see a param called hide_empty
. This is the parameter which plays major role in this case.
hide_empty - (bool|int) Whether to hide terms not assigned to any posts. Accepts 1|true or 0|false. Default 1|true.
To get all the terms which is added to the custom taxonomy we need to set this parameter as false
.
get_terms(
'mycustom_taxonomy',
array(
'hide_empty' => false
)
);
This will give you all the terms even though it is not added to any post.