Elementor add_control generate unique id

Viewed 483

I have an elementor widget and it has a hidden field in settings. I want to this to be a random number generated every time a new widget is created. And I need this to be saved like other fields.

I tried like this but when I drag second widget out it has the same random number generated as the first widget.

protected function _register_controls() {

$this->add_control(
    'instanceId',
    [
        'show_label' => false,
        'type' => \Elementor\Controls_Manager::HIDDEN,
        'default' => rand(10,9999999)
    ]
);

... other fields

}

How can I achieve this?

1 Answers

I also faced this problem and here is my solution: First, you need to create a new function inside the widget class. pay attention that the most important part here is to set the function as private:

<?php
// Elementor Widget Class
class Elementor_wocmlm_Widget extends \Elementor\Widget_Base {

// The basic elementor functions like public function get_name()
...

// The uniq id function
private function uniqId(){  
return uniqid('prefix-'); 

// close class
    }

And than you can directly use this function inside render() protected function like this:

    protected function render() {

        //Sign the private function as a variable
        $uniqID = $this->uniqId();

        //Use It
        echo '
        <style> 
        body '. esc_html($uniqID) .' .div { background:#000; } 
        </style>
        ';

}

Full Code:

<?php
// Elementor Widget Class
class Elementor_wocmlm_Widget extends \Elementor\Widget_Base {

// The basic elementor functions like public function get_name()
...

// The uniq id function
private function uniqId(){  
return uniqid('prefix-'); 

    protected function render() {

        //Sign the private function as a variable
        $uniqID = $this->uniqId();

        //Use It
        echo '
        <style> 
        body '. esc_html($uniqID) .' .div { background:#000; } 
        </style>
        ';

}
// close class
    }

NOTE: You can replace uniqid('prefix-') with rand(10,9999999) but it does not say that you will not get the same number for two different widgets, better use uniqid()..

Related