Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This piece of code gets the categories used by a list of posts in Wordpress, this also can be filtered to only show categories that are children of an specific category
* This function will return a list of categories used by a group of posts ids
* @param string $taxonomy The name of the taxonomy to search for
* @param array $objects_id The list of posts IDs to check against
* @param integer $child_of A parent category to limit the search on
* @return array A list of terms
* @example getAssociatedTerms( 'product_cat', [ 16, 22, 32 ] )
function getAssociatedTerms( $taxonomy = '', array $objects_id = [], $child_of = 0 ) {
$args = [
'taxonomy' => $taxonomy,
'object_ids' => $objects_id,
'child_of' => $child_of,
'hide_empty' => true
$query = new WP_Term_Query( $args );
return $query->get_terms();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment