- Trả về tên/đối tượng taxonomy có gán vào post type.
//get taxonomy name for given post type
$taxonomy_names = get_object_taxonomies( 'post' );
print_r( $taxonomy_names);
//get taxonomy objects for given post type
$taxonomy_objects = get_object_taxonomies( 'post', 'objects' );
|
Kết quả ví dụ:
Array
(
[0] => category
[1] => post_tag
[2] => post_format
)
- Lấy toàn bộ dữ liệu terms của một taxonomy.
$taxonomies = array(
'post_tag',
'my_tax',
);
$terms = get_terms($taxonomies);
foreach ( $terms as $term ) {
echo '<li><a href="'.get_term_link( $term ).'">' . $term->name . '</a></li>';
}
//ordered by count
$categories = get_terms( 'category', 'orderby=count&hide_empty=0' );
#other way with array
$categories = get_terms( 'category', array(
'orderby' => 'count',
'hide_empty' => 0,
) );
|
- Kiểm tra category có sub-categories.
Cách 1: Xem đoạn code mẫu bên dưới.
$children = get_term_children($termId, $taxonomyName);
if( empty( $children ) ) {
//do something here
}
<?php
$term_id = 10;
$taxonomy_name = 'products';
$termchildren = get_term_children( $term_id, $taxonomy_name );
echo '<ul>';
foreach ( $termchildren as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
}
echo '</ul>';
?>
|
Cách 2: Kiểm tra nếu category hiện tại có subcategories.
$term = get_queried_object();
$children = get_terms( $term->taxonomy, array(
'parent' => $term->term_id,
'hide_empty' => false
) );
// print_r($children); // uncomment to examine for debugging
if($children) { // get_terms will return false if tax does not exist or term wasn't found.
// term has children
}
|
- Xác định category mẹ của một category nếu có:
//firstly, load data for your child category
$child = get_category(31);
//from your child category, grab parent ID
$parent = $child->parent;
|
- Lấy dữ liệu custom fields của category.
$term_id = 12345;
$term_meta = get_option( 'taxonomy_' . $term_id );
$my_cf = $term_meta[ 'my_cf' ];
echo $my_cf;
|