Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save evgrezanov/6a8bd6eb479ef6627594d45ee2d67227 to your computer and use it in GitHub Desktop.
Save evgrezanov/6a8bd6eb479ef6627594d45ee2d67227 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment