How to get the Widget ID in wordpress

In this Post I will share a short snippet which will display the widget id inside the widget form.

One can also get the widget id by inspecting the html but I find that rather tedious and user unfriendly.  So I wrote this short snippet. All you need to do is include it on your site and every widget form will display the widget-id.

Refer to the screenshot below.

Display widget ID

Snippet

Here is the snippet. Simply paste it in your functions.php file and you are good to go. You may also use the code snippet plugin.

add_action('in_widget_form', 'spice_get_widget_id');

function spice_get_widget_id($widget_instance)

{
    
    // Check if the widget is already saved or not. 
    
    if ($widget_instance->number=="__i__"){
     
     echo "<p><strong>Widget ID is</strong>: Pls save the widget first!</p>"   ;
    
    
  }  else {

        
       echo "<p><strong>Widget ID is: </strong>" .$widget_instance->id. "</p>";
         
 
    }
}

 

Basically we simple hook into the in_widget_form  filter and then echo the widget id.  To be doubly sure we first check if the widget instance actually exists.

Plugin

I created a plugin based on this tutorial. In case you are not comfortable with coding then simply download and install this plugin.  Here is the link 

Conclusion

As you can see its really simple to get the widget id. Just use this small snippet and save yourself some time 🙂

Did you enjoy this article?
Get Awesome with WordPress. Subscribe and get awesome stuff delivered straight to your inbox.
I agree to have my personal information transfered to Mad Mimi ( more information )

4 thoughts on “How to get the Widget ID in wordpress

  1. Great snippet – thanks a lot!
    Here’s a mod for making strings translatable – for everyone, who may need it:

    // Function for displaying widget ids on widget admin page
    function spice_get_widget_id($widget_instance) {
    // Check if the widget is already saved or not.
    if ($widget_instance->number=="__i__"){
    echo "" . __( 'Widget ID is', 'pxelegance' ) . ": " . __( 'Pls save the widget first!', 'pxelegance' ) . "";
    } else {
    echo "" . __( 'Widget ID is', 'pxelegance' ) . ": " .$widget_instance->id. "";
    }
    }
    add_action('in_widget_form', 'spice_get_widget_id');

Leave a Comment