# Hướng dẫn sử dụng  hàm get\_terms (ok)

Trước tiên, get\_terms nó là một hàm (function), còn WP\_Term\_Query nó là một lớp (class), nên tùy mục đích sử dụng mà chúng ta có thể sử dụng function hay là class. Bài viết này Huy Hòa chỉ hướng dẫn các bạn sử dụng hàm. Nếu có thời gian rảnh, mình sẽ viết hướng dẫn sử dụng lớp (class) sau. Tuy nhiên, với lớp WP\_Term\_Query thì phạm vi áp dụng nó mở rộng hơn và nó hoàn toàn có thể thay thế get\_terms được.

Table of Contents \[[show](https://huyhoa.net/su-dung-get-terms-wordpress/#)]

### Hàm get\_terms() nằm ở đâu?

Hàm này nằm ở trong core nguồn của [WordPress](https://huyhoa.net/topic/wordpress/).  Các bạn có thể tìm thấy hàm này tại file này: ***wp-includes/taxonomy.php***. Đây là hàm nguyên bản của WordPress:

```
function get_terms( $args = array(), $deprecated = '' ) {
    $term_query = new WP_Term_Query();
 
    $defaults = array(
        'suppress_filter' => false,
    );
 
    /*
     * Legacy argument format ($taxonomy, $args) takes precedence.
     *
     * We detect legacy argument format by checking if
     * (a) a second non-empty parameter is passed, or
     * (b) the first parameter shares no keys with the default array (ie, it's a list of taxonomies)
     */
    $_args          = wp_parse_args( $args );
    $key_intersect  = array_intersect_key( $term_query->query_var_defaults, (array) $_args );
    $do_legacy_args = $deprecated || empty( $key_intersect );
 
    if ( $do_legacy_args ) {
        $taxonomies       = (array) $args;
        $args             = wp_parse_args( $deprecated, $defaults );
        $args['taxonomy'] = $taxonomies;
    } else {
        $args = wp_parse_args( $args, $defaults );
        if ( isset( $args['taxonomy'] ) && null !== $args['taxonomy'] ) {
            $args['taxonomy'] = (array) $args['taxonomy'];
        }
    }
 
    if ( ! empty( $args['taxonomy'] ) ) {
        foreach ( $args['taxonomy'] as $taxonomy ) {
            if ( ! taxonomy_exists( $taxonomy ) ) {
                return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
            }
        }
    }
 
    // Don't pass suppress_filter to WP_Term_Query.
    $suppress_filter = $args['suppress_filter'];
    unset( $args['suppress_filter'] );
 
    $terms = $term_query->query( $args );
 
    // Count queries are not filtered, for legacy reasons.
    if ( ! is_array( $terms ) ) {
        return $terms;
    }
 
    if ( $suppress_filter ) {
        return $terms;
    }
 
    /**
     * Filters the found terms.
     *
     * @since 2.3.0
     * @since 4.6.0 Added the `$term_query` parameter.
     *
     * @param array         $terms      Array of found terms.
     * @param array         $taxonomies An array of taxonomies.
     * @param array         $args       An array of get_terms() arguments.
     * @param WP_Term_Query $term_query The WP_Term_Query object.
     */
    return apply_filters( 'get_terms', $terms, $term_query->query_vars['taxonomy'], $term_query->query_vars, $term_query );
}
```

Đây cũng là hàm nằm trong core của WordPress nên ta chỉ việc sử dụng nó, còn phát triển và bảo mật là việc của …Wordpress lo.

### Cách sử dụng hàm get\_terms()

Kể từ phiên bản WordPress 4.5 cách sử dụng của hàm get\_terms() có thay đổi chút.

```
$taxonomies = get_terms( array(
    'taxonomy' => 'taxonomy_name',
    'hide_empty' => false
) );
```

Trong đó:

**taxonomy:** Giá trị truyền vào nhằm xác định tham số cần lấy thông tin.

**hide\_empty**:  Mặc định thì nó không lấy các “terms” mà không được gán với bài viết cụ thể nào. Nếu bạn vẫn muốn nó trả về những terms không gắn với bài viết nào thì bạn có thể chuyển cái false kia thành true là được

![](/files/-MOjbHsLeqqcQETX4Dh5)

Các tham số có thể truyền vào của hàm get\_terms là:

```
    'taxonomy' => '', 
    'orderby' => 'name', 
    'order' => 'ASC', 
    'hide_empty' => 1, 
    'include' => array(), 
    'exclude' => array(), 
    'exclude_tree' => array(), 
    'number' => '', 
    'offset' => 0, 
    'fields' => 'all', 
    'name' => '', 
    'slug' => '', 
    'hierarchical' => true, 
    'search' => '', 
    'name__like' => '', 
    'description__like' => '', 
    'pad_counts' => false, 
    'get' => '', 
    'child_of' => 0, 
    'parent' => '', 
    'childless' => false, 
    'cache_domain' => 'core', 
    'update_term_meta_cache' => true, 
    'meta_query' => null, 
    'meta_key' => ''
```

Khi sử dụng hàm này cho các custom field thì có thể sử dụng như ví dụ này:

```
$terms = get_terms( 'my_term', $args );
```

Trong đó my\_term là tên của taxonomy. Ví dụ như: Thể loại tour / Hạng tàu

```
Giá trị trả về
Hàm get_terms() trả về một đối tượng WP_Post (WP_Post object).  Các thông số trả về như danh sách bên dưới đây:

[“term_id”]=> //int
[“name”]=> //string
[“slug”]=> //string
[“term_group”]=> //int
[“term_taxonomy_id”]=> //int
[“taxonomy”]=> //string
[“description”]=> //string
[“parent”]=> //int
[“count”]=> // int
[“filter”]=> //string
[“meta”]=> array(0)
Từ danh sách trả về đó, chúng ta hoàn toàn có thẻ lấy riêng từng giá trị hoặc lấy tất cả. Dưới đây là một ví dụ việc hiện tất cả các category theo kiểu dropdown list:
```

```
<?php
function hhlist_taxonomy($type, $post_type) {
  $terms = get_terms($type);
  $category = taxonomy_current($type); 
  if ( !empty( $terms ) && !is_wp_error( $terms ) ){
    the_terms_list(
      'categories__dropdown icon-dropdown',
      array(
        'show_option_all'  => 'Click to filter',
        'taxonomy'         => $type,
        'current_category' => $category->term_id,
        'value_field'      => 'slug',
        'selected'         => $category->slug,
      ),
      'dropdown',
      'data-module-init="redirect-dropdown"'
    );
  }
}
?>
```

### get\_terms() exclude

```
Tương tự như vậy, mình có thể giới hạn terms cần lấy bằng cách dùng exclude trong tham số $args truyền vào. Ví dụ dưới đây là mình list tất cả các category của HuyHoa.Net nhưng loại trừ (exclude) 2 category có ID là 30 và 1.
```

```
<?php
$hh_taxonomies = get_terms( array(
    'taxonomy' => 'category',
    'exclude' => array(30,1),
    'hide_empty' => false
) ); 
if ( !empty($hh_taxonomies) ) :
    $output = '<select>';
    $output .= '<option>Chọn danh mục</option>';
    foreach( $hh_taxonomies as $cat_hh ) {
        if( $cat_hh->parent == 0 ) {
            $output.= '<optgroup label="'. esc_attr( $cat_hh->name ) .'">';
            foreach( $hh_taxonomies as $subcategory ) {
                if($subcategory->parent == $cat_hh->term_id) {
                $output.= '<option value="'. esc_attr( $subcategory->term_id ) .'">
                    '. esc_html( $subcategory->name ) .'</option>';
                }
            }
            $output.='</optgroup>';
        }
    }
    $output.='</select>';
    echo $output;
endif;
//var_dump($hh_taxonomies);
?>
```

#### get\_terms exclude by slug

```
Nếu bạn muốn exclude một số giá trị slug khi dùng get terms thì nó phức tạp hơn chút. Trước tiên bạn phải dùng chính get terms để lấy các giá trị id của slug cần loại, sau đó mới dùng get terms để lấy giá trị cần lấy. Đọc đoạn code dưới đây để hiểu rõ ý định của mình trong đoạn code 
```

```
<?php
// default to not exclude terms
$ids_to_exclude = array();
$get_terms_to_exclude =  get_terms(
    array(
        'fields'  => 'ids',
        'slug'    => array( 
            'du-lich', 
            'travel', 
            'web',
            'seo' ),
        'taxonomy' => 'post_tag',
    )
);
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'   => 'post_tag',
    )
);
if ( count($roles) > 0 ) : ?>
     // làm gì ở đây thì làm :D
<?php endif;?>
```

### get\_terms parent – depth

```
Nếu bạn truyền tham số ‘parent’ => 0 thì nó sẽ chỉ lấy các terms cha mẹ. Còn các terms con nó không lấy. Ví dụ :
```

```
$myterms = get_terms( array( 'taxonomy' => 'category', 'parent' => 0 ) );
```

#### get\_terms depth – get only top-level terms in a custom taxonomy

Chọn parent thành 0 là nó chỉ lấy toàn bộ terms cha mẹ mà không hiện terms con như ví dụ bên trên ấy

```
$terms = get_terms( array( 
    'taxonomy' => 'tax_name',
    'parent'   => 0
) );
```

#### List the child terms of a taxonomy and not their parents

Dựa vào cái parent này thì mình hoàn toàn có thể chỉ hiện nguyên các terms con, không hiện terms cha mẹ. Đây là ví dụ cụ thể:

```
<?php
$taxonomyName = "category";
//This gets parent terms only.  This is done by setting parent to 0.  
$parent_terms = get_terms( $taxonomyName, array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => false ) );   
echo '<ul>';
foreach ( $parent_terms as $pterm ) {
    //Get the Child terms
    $terms = get_terms( $taxonomyName, array( 'parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false ) );
    foreach ( $terms as $term ) {
        echo '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>';   
    }
}
echo '</ul>';
?>
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learnphp.gitbook.io/learnphp/wordpress/huong-dan-su-dung-ham-get_terms-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
