Skip to content

Instantly share code, notes, and snippets.

@rdeeb
Last active May 6, 2018 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdeeb/71b8a2150ef2b1162ffbab63c5dec965 to your computer and use it in GitHub Desktop.
Save rdeeb/71b8a2150ef2b1162ffbab63c5dec965 to your computer and use it in GitHub Desktop.
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
<?php
/**
* 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