'Randome background for elementor

I use Elementor pro in my site. I have big Background image in top of my homepage that I have many elements in that section. I want to have one random image from a group of images (can be in gallery or in folder). but i didn't fine any solution.

I tried any addon for elementor. elementor pro background slidet, the plus row background, and etc. but they only make a slides with default order and don't have random order. I also tried some slider plugin or elementor's slider addons (smart slider,...). but the elements that should be on the image (other than text and buttons) could not be added to them.

I tried some javascripts to do it (for example: https://element.how/elementor-slider-random/#comment-12854 and this: Random background image on refresh). but it didn't work.

I like to know there is any solution to use custom php code to elementor dynamic simple background image that apply all background setting?

is there any solution?



Solution 1:[1]

protected function render() {
    $settings = $this->get_settings_for_display();

    $images = array_values( $settings['carousel'] ?? [] );
    if ( ! $images ) {
        return;
    }
    $count = count( $images );
    $image = random_int( 0, ( $count - 1 ) );
    $image = $images[ $image ] ?? null;
    if ( ! $image ) {
        return;
    }

    $image_url = Group_Control_Image_Size::get_attachment_image_src( $image['id'], 'full', [ 'full_size' => 'full' ] );

    echo '<img class="' . $this->get_name() . '-image" src="' . esc_attr( $image_url ) . '" alt="' . esc_attr( Control_Media::get_image_alt( $image ) ) . '" />';
}

Elementor create a custom widget and follow the code. I hope your problem will be solved.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1