How to output the taxonomy term name in a widget

I have a taxonomy for example “country” and I want to simply display the term in the side bar eg. New Zealand.
There is only one possible taxonomy per post so I don’t need to create a list or anything. Any ideas?

Related posts

Leave a Reply

1 comment

  1. 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.