Querying WordPress Taxonomy Terms
Get the Name and URL for All Terms Associated with a WordPress Taxonomy
Use the get_terms()
function to get the terms associated with a taxonomy where 'my-taxonomy-name'
is the taxonomy key registered in register_taxonomy()
.
$terms = get_terms( 'my-taxonomy-name' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
$term_link = get_term_link( $term );
echo esc_url( $term_link );
echo wp_kses_post( $term->name );
}
}
Retrieve Only the Parent Terms When the Taxonomy is Hierarchical
Add the argument 'parent' => 0
to the array of options when running get_terms()
:
$terms = get_terms( 'my-taxonomy-name' , array( 'parent' => 0 ) );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
echo wp_kses_post( $term->name ) . "\n";
}
}
Using WP_Term_Query
Instead of get_terms()
for Greater Control
Query the 15 most used terms in descending order of use:
$term_query = new \WP_Term_Query( array(
'taxonomy' => 'my-taxonomy-name',
'orderby' => 'count',
'order' => 'DESC',
'fields' => 'all',
'hide_empty' => true,
'number' => 15,
) );
if ( ! empty( $term_query->terms ) ) {
foreach ( $term_query->terms as $term ) {
$term_link = get_term_link( $term );
echo esc_url( $term_link );
echo wp_kses_post( $term->name );
}
}
Get All Children of a Hierarchical WordPress Taxonomy
Use the get_term_children()
function to get the children of a term where the $term_id
, is the ID of the parent term (which might be retrieved on an individual page via get_the_ID()
for example) and the $my-taxonomy-name
is the taxonomy key registered in register_taxonomy()
.
<?php
$term_id = 123;
$my_taxonomy_name = 'spam';
$termchildren = get_term_children( $term_id, $my_taxonomy_name );
foreach ( $termchildren as $child ) {
$term = get_term_by( 'id', $child, $my_taxonomy_name );
echo wp_kses_post( $term->name );
}
Additional Resources
Smashing Magazine has a great article on setting up and using custom taxonomies which covers the get_terms()
function and using the WP_Query()
class.
Feedback?
Email us at enquiries@kinsa.cc.