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.

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;

                });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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