Universal shortcode to output standard and custom fields of terms on a taxonomy archive page

This is a generic taxonomy shortcode which will work both outside of the loop and within the loop on the taxonomy archive pages, and depending on the attributes you provide you can output any of the taxonomy (slug), the term name, the term slug, the term id, the term description, the count of results, or you can also use it to output term meta for the current term by specifying the field.

Here’s the code to register the shortcode:

/**
 * Register shortcode to output current taxonomy
 * for use on taxonomy archive page outside or inside loop
 * att['output'] string taxonomy | name (default) | slug | term_id | description | count | field (requres att['field'])
 * att['field'] string key
 */
add_shortcode('taxonomy', function ($atts = [], $content = null) {
 
    // provide defaults
    $atts = shortcode_atts(
        array(
            'output' => 'name',
            'field' => '',
        ),
        $atts
    );
    extract($atts);
 
    $return = '';
 
    global $wp_query;
    $obj = $wp_query->get_queried_object();
 
    if ($output != 'field') {
 
        $return = $obj->$output;
    } else {
        if (isset($field)) {
            $return = get_term_meta($obj->term_id, $field, true);
        }
    }
 
    return $return;
});

And here are examples of how to use it:

[taxonomy output='taxonomy'] -- outputs the taxonomy slug
[taxonomy] -- outputs the term name (default)
[taxonomy output='count'] -- outputs the count of results
[taxonomy output='field' field='wpcf-colour'] -- outputs a 'colour' taxonomy custom field

Support Thread Example

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments