Skip to content

Instantly share code, notes, and snippets.

@dan-westall
Last active August 9, 2017 01:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dan-westall/5471643 to your computer and use it in GitHub Desktop.
Save dan-westall/5471643 to your computer and use it in GitHub Desktop.
Allowing wp_get_object_terms to exclude terms with a filter.
<?php
///////Example usage//////////
//get object terms for $post->ID with taxonomies categories and tags,
//args set as fields all and exclude term with id 1
$terms = wp_get_object_terms(
$post->ID,
array(
'category',
'post_tag'
),
array(
'fields' => 'all',
'exclude' => array(1)
)
);
///////Filter function//////////
function wp_get_object_terms_exclude_filter($terms, $object_ids, $taxonomies, $args) {
//if exclude is set and fields is set to all go
if(isset($args['exclude']) && $args['fields'] == 'all') {
//loop through terms
foreach($terms as $key => $term) {
//loop through exclude terms
foreach($args['exclude'] as $exclude_term) {
//if exlude term matches current object term unset
if($term->term_id == $exclude_term) {
unset($terms[$key]);
}
}
}
}
//reset keys, because of unset.
$terms = array_values($terms);
return $terms;
}
add_filter('wp_get_object_terms', 'wp_get_object_terms_exclude_filter', 10, 4);
@lonchbox
Copy link

thnx for this, It realy help me! :)

@zukezuko
Copy link

zukezuko commented Jul 7, 2014

Thank you!!!!!
works as advertized.

@dchatchet
Copy link

So beautiful, don't know how this isn't native... THANKS!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment