5

I'm trying to output a unique widget ID inside my mult-instance widgets. So far the following hasn't worked. Is there a unique ID and how do I call it?

Thanks.

function widget($args, $instance) {
// outputs the content of the widget
    extract( $args );
    $widget_id = $instance['widget_id'];    
?>
<?php echo $widget_id ; ?>
<?php
}

Thanks.

3 Answers 3

13

You can get the instance ID with echo $this->id; ($this is the class instance)

The only time you can't get this id is from the form() function, right after you just dropped the widget (here's the reason why)

0

To print the ID in php:

echo $this->id;

But this will also print the id before it has been added to the sidebar.

So the id will correspond to widget-[#]_my_widget-__i__

A complementary way to get the widget id is in javascript, after it has been added:

$(document).on('widget-added', function(event, widget){
                    var widget_id = widget.context.id;

                });
0

The accepted answer no longer works with recent versions of Elementor (Testing on 3.18.3 2023).

Updated method for getting the widget ID:

$this->get_id();
2
  • You should explain, wy do you think that this is the correct answer so OP can not only use it, but also understand it. Commented Jan 10 at 10:07
  • @KrzysiekDróżdż because the accepted answer no longer works with recent versions of Elementor. So I added this here for people finding this page in search results and realising that it doesn't work. Commented Jan 10 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.