How To get a WordPress Widget ID for Multiple Instances

Supporting Multiple Widget Instances

Just recently I was developing a WordPress widget, and as I began coding of all my use cases I realized that I needed to be able to support multiple widget instances.  Supporting multiple widget instances is not a big deal, unless you plugin depends on knowing the widget id from the front-end.  By this I mean after your page has loaded, you need to perform client-side scripting that depends on knowing the id of each widget instance.

Where is the Widget’s Instance ID stored?

/** @see WP_Widget::widget */
function widget($args, $instance) {
    echo $this->id;

Using the id property of the WP_Widget class we can determine the id of each widget instance.  This can then be used in the widget function.  You can add a hidden input field with the value containing the id of the widget instance.

/** @see WP_Widget::widget */
function widget($args, $instance) {
    echo '<input class="your_unique_class" style="display: none;" type="text" value="' . $this->id . '" />;

Then you can access all the id with:

jQuery(document).ready(function($) {
     var widget_ids = $(".your_unique_class");
     for (var x = 0; x < widget_ids.length; x++) {

3 thoughts on “How To get a WordPress Widget ID for Multiple Instances”

  1. I’d love to see a working example of this. I’m about to start figuring out how to dynamically build the menu for a tab list based on the IDs of the widgets in a widget area. For example if the user adds three text widgets to a widget area, I need to dynamically build the ul and target the IDs of the widgets…

  2. i just finding the way how to show a different color in each widget by using jQuery.but can’t figure out how to get unqie ID for each widget and this post really help me to get my exact result 🙂

Leave a Reply