I have a custom taxonomy “role” for my custom post type “People”.
When listing the roles, is there a way to exclude roles based on slug and not ID via get_terms
function?
I ask because I’m running a multisite and a few websites have the same IDs as the ones I’d like to exclude.
Right now I have:
<?php
$roles = get_terms(
'role', array(
'orderby' => 'ID',
'order' => 'ASC',
'hide_empty' => true,
'exclude' => array('58', '63', '833'),
));
$count_roles = count($roles);
if ( $count_roles > 0 ) : ?>
//do stuff
<?php endif;?>
The slugs I’d like to exclude are: 'slug' => ['graduate', 'job-market-candidate', 'graduate-student','research']
, but I don’t know where to fit this line, if anywhere.
Any help is appreciated!
2 Answers
The get_terms()
(see docs) function accepts the same args as WP_Term_Query
(see docs)
You have to get those terms Ids first and then pass it to the exclude
arg:
// default to not exclude terms
$ids_to_exclude = array();
$get_terms_to_exclude = get_terms(
array(
'fields' => 'ids',
'slug' => array(
'graduate',
'job-market-candidate',
'graduate-student',
'research' ),
'taxonomy' => 'role',
)
);
if( !is_wp_error( $get_terms_to_exclude ) && count($get_terms_to_exclude) > 0){
$ids_to_exclude = $get_terms_to_exclude;
}
$roles = get_terms(
array(
'orderby' => 'ID',
'order' => 'ASC',
'hide_empty' => true,
'exclude' => $ids_to_exclude,
'taxonomy' => 'role',
)
);
$count_roles = count($roles);
if ( $count_roles > 0 ) : ?>
//do stuff
<?php endif;?>