How to output the taxonomy term name in a widget

Check the properties of get_queried_object().

Sample code:

<?php # -*- coding: utf-8 -*-
/**
 * Plugin Name: Current Term Widget
 */

add_action( 'widgets_init', array ( 'Current_Term_Widget', 'register' ) );

class Current_Term_Widget extends WP_Widget
{
    public function __construct()
    {
        parent::__construct( 'current_term', 'Current Term' );
    }
    public function widget( $args, $instance )
    {
        if ( isset ( get_queried_object()->taxonomy )
            && isset( get_queried_object()->name )
        )
        {
            return print $args['before_widget']
                . '<b style="padding:10px;border:3px solid red">'
                . get_queried_object()->name
                . '</b>'
                . $args['after_widget'];
        }
    }
    public static function register()
    {
        register_widget( __CLASS__ );
    }
}

Here is a screen shot for the archive of category Cat B from the test data:

enter image description here

To restrict the widget output to a taxonomy compare get_queried_object()->taxonomy with your registered taxonomy name.

Leave a Comment