Using WordPress ‘get_the_taxonomies()’ PHP function

The get_the_taxonomies() WordPress PHP function retrieves all taxonomies associated with a post.

Usage

get_the_taxonomies( $post, $args );

Custom example:

get_the_taxonomies( 42, array( 'template' => 'Taxonomy: %s', 'term_template' => '<a href="%1$s">%2$s</a>' ) );

Parameters

  • $post (int|WP_Post, Optional) – Post ID or WP_Post object. Default is global $post.
  • $args (array, Optional) – Arguments about how to format the list of taxonomies.
    • template (string) – Template for displaying a taxonomy label and list of terms. Default is “Label: Terms.”
    • term_template (string) – Template for displaying a single term in the list. Default is the term name linked to its archive.

More information

See WordPress Developer Resources: get_the_taxonomies()

Examples

Displaying post taxonomies

This example displays all taxonomies associated with the current post in the loop.

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        $taxonomies = get_the_taxonomies();
        foreach ( $taxonomies as $taxonomy ) {
            echo $taxonomy;
        }
    }
}

Displaying custom taxonomies

This example displays custom taxonomies associated with a specific post ID.

$post_id = 42;
$taxonomies = get_the_taxonomies( $post_id );
foreach ( $taxonomies as $taxonomy ) {
    echo $taxonomy;
}

Modifying taxonomy display

This example modifies how taxonomies are displayed using custom templates.

$args = array(
    'template' => '<strong>%s:</strong> %l',
    'term_template' => '<a href="%1$s">%2$s</a>'
);
$taxonomies = get_the_taxonomies( null, $args );
foreach ( $taxonomies as $taxonomy ) {
    echo $taxonomy;
}

Displaying taxonomies for custom post type

This example displays taxonomies for a custom post type.

$args = array(
    'post_type' => 'my_custom_post_type',
);
$custom_posts = new WP_Query( $args );

if ( $custom_posts->have_posts() ) {
    while ( $custom_posts->have_posts() ) {
        $custom_posts->the_post();
        $taxonomies = get_the_taxonomies();
        foreach ( $taxonomies as $taxonomy ) {
            echo $taxonomy;
        }
    }
}

Removing taxonomy name

This example removes the taxonomy name for a plugin that extracts words for static search.

add_filter( 'wp_sprintf', function( $fragment ) {
    $fragment = ( '%z' === $fragment ) ? '' : $fragment;
    return $fragment;
} );

while ( have_posts() ) {
    the_post();
    $terms = get_the_taxonomies( 0, array( 'template' => '%z%l', 'term_template' => '%2$s' ) );
    echo implode( ' ', $terms );
}