如何通过术语名称而不是术语 ID 从 get_terms 中排除术语

How can exclude term from get_terms by term name not by term id

下面是我的代码。使用条款删除不起作用。我需要它像这样工作,而不是通过 ID 删除。

$terms = get_terms( 'MY_TAXONOMY', array( 
                        'orderby' => 'name',
                        'order'   => 'ASC',
                        'exclude'  => array(),
) );
$exclude = array("MY TERM", "MY TERM 2", "MY TERM 3");
$new_the_category = '';
foreach ( $terms as $term ) {
    if (!in_array($term->term_name, $exclude)) {
        $new_the_category .= '<div class="post hvr-grow"><li><strong><a id="lista" href="'.esc_url( get_term_link( $term ) ) .'">'.$term->name.'</a>'. ' ('. $term->count . ')</strong></li></div>';
    }
}
echo substr($new_the_category, 0);

您可以通过在您想要省略的条款上使用 get_term_by() 来获得您想要排除的 term_ids。然后您可以将这些 ID 作为排除参数传递。

请注意,get_terms() 中的第二个 $args 数组已被弃用,因此您应该将 MY_TAXONOMY 移动到键为 taxonomy 的参数中。

另外我不确定你为什么要回显一个从 0 开始没有终点的子字符串,所以我删除了它。我还删除了变量连接,只是在 foreach 循环中回显了字符串。

$exclude_ids   = array();
$exclude_names = array("MY TERM", "MY TERM 2", "MY TERM 3"); // Term NAMES to exclude

foreach( $exclude_names as $name ){
    $excluded_term = get_term_by( 'name', $name, 'MY_TAXONOMY' );
    $exclude_ids[] = (int) $excluded_term->term_id; // Get term_id (as a string), typcast to an INT
} 

$term_args = array(
    'taxonomy' => 'MY_TAXONOMY',
    'orderby' => 'name',
    'order'   => 'ASC',
    'exclude' => $exclude_ids
);

if( $terms = get_terms( $term_args ) ){
    // If we have terms, echo each one with our markup.
    foreach( $terms as $term ){
        echo '<div class="post hvr-grow"><li><strong><a id="lista" href="'.esc_url( get_term_link( $term ) ) .'">'.$term->name.'</a>'. ' ('. $term->count . ')</strong></li></div>';
    }
}

您的代码工作正常,只需将 $term->term_name 替换为 $term->name 然后它应该工作正常。请参阅下面的代码以供参考。

$terms = get_terms( 'MY_TAXONOMY', array( 
                        'orderby' => 'name',
                        'order'   => 'ASC',
                        'exclude'  => array(),
) );
$exclude = array("MY TERM", "MY TERM 2", "MY TERM 3");
$new_the_category = '';
foreach ( $terms as $term ) {
if (!in_array($term->name, $exclude)) {
$new_the_category .= '<div class="post hvr-grow"><li><strong><a id="lista" href="'.esc_url( get_term_link( $term ) ) .'">'.$term->name.'</a>'. ' ('. $term->count . ')</strong></li></div>';
}
}
echo substr($new_the_category, 0);