簡體   English   中英

如何通過術語名稱而不是術語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);

你可以得到term_ids要使用排除者的get_term_by()你想省略的條款。 然后,您可以將這些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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM