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.
This is how it will appear
Snippet
Here is the snippet.
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>";
}
}
Simply paste it in your functions.php file and you are good to go. You may also use the code snippet plugin.
Infact I highly Recommend using Code Snippets plugin for adding snippets to your wordpress website. It is not a good idea to make edits to your theme functions.php as the modification which get overwritten when you update the theme.
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.
Using a Plugin Instead
Some of the readers asked if there is a plugin to achieve this. So
I created a plugin based on this tutorial.
In case you are not comfortable with coding then simply download and install the Get Widget ID Plugin
Conclusion
As you can see its really simple to get the widget id. Just use this small snippet and save yourself some time 🙂
- How to create 301 Redirects in WordPress - December 21, 2019
- How to Filter Blog Posts by Author in WordPress Admin panel - October 21, 2019
- How to convert / change post type in wordpress - October 21, 2019
How do I get content of register_widget Id ?
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');
I just see that the code-tag adds more ” than needed – Ankit, would be nice if you can correct the output 🙂
Thanks