代码之家  ›  专栏  ›  技术社区  ›  J.Z

如何按术语名称而不是按术语ID从“获取术语”中排除术语

  •  1
  • J.Z  · 技术社区  · 6 年前

    我下面的代码。使用这些术语删除是行不通的。我需要它这样工作,而不是按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);
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Mukesh Panchal    6 年前

    您的代码工作正常,只需要替换 $term->term名称 $term->名称 那它就可以工作了。参考以下代码。

    $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);
    
        2
  •  1
  •   Xhynk    6 年前

    你可以得到 term_ids 通过使用排除在外的 get_term_by() 根据你想要省略的条款。然后可以将这些ID作为exclude参数传递。

    作为注释,第二个 $args 数组输入 get_terms() 已被弃用,因此应移动 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>';
        }
    }