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.

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?
We regularly publish WordPress related Tutorials and Tips on this blog. Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to Mad Mimi ( more information )
About Ankit

Founder of SpiceWp. We share useful Wordprss Tips and Tricks.

I have also released 17 Wordpress Plugins till date .

I regularly publish Wordpress related Tutorials and Tips on this blog.
If you like the content then consider subscribing to the blog here.

Comments

  1. How do I get content of register_widget Id ?

  2. 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');

  3. I just see that the code-tag adds more ” than needed – Ankit, would be nice if you can correct the output 🙂
    Thanks

Speak Your Mind

*