widgetWe know that widgets are important part of wordpress. We use widgets in different ways to show our content at front end. Generally we use wordpress widgets to show our required parts in our sidebar, footer, header etc parts of the website, but few developers want to use it for many other functionalities. As it is a very flexible part for the developers, so they wants to use it in any part of the website as per the requirement.
 
Sometimes we need the ID of any widget while working with them, because if we get the ID then we can easily get its content and this make our work easy. But sometimes getting the widget ID id takes a little of our valuable time. So, here I am sharing the code to get the widget ID easily by adding a small code snippet.

Just add the below mentioned code at the end of your functions.php file :

add_action('in_widget_form', 'yatendra_get_widget_id'); //hookiing our function to "in_widget_form" hook

function yatendra_get_widget_id($widget_instance)

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

        //get the widget ID

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

In the above code we are using “in_widget_form” hook which fires at the end of the widget control form. Generally we use this hook to add any extra field at the end of the widget form.

When anyone use this code then the ID of all the widgets will show in widgets are at Admin => Appearance => Widgets. Look at the image above, which is showing the correct location where the widget Id is showing.

This code may save anyone’s time 🙂