How to render a media control for an image in Elementor widgets?
We can render a media control for print the image URL in a custom <img>
tag. For the same we can use wp_get_attachment_image() function to generate the image markup. The following code is example of rendering a media contorl for image.
<?php
class Elementor_Test_Widget extends \Elementor\Widget_Base {
protected function register_controls() {
$this->start_controls_section(
'section_content',
[
'label' => esc_html__( 'Content', 'textdomain' ),
'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
]
);
$this->add_control(
'image',
[
'label' => esc_html__( 'Choose Image', 'textdomain' ),
'type' => \Elementor\Controls_Manager::MEDIA,
'default' => [
'url' => \Elementor\Utils::get_placeholder_image_src(),
],
]
);
$this->end_controls_section();
}
protected function render() {
$settings = $this->get_settings_for_display();
// Get image url
echo '<img src="' . esc_url( $settings['image']['url'] ) . '" alt="">';
// Get image by id
echo wp_get_attachment_image( $settings['image']['id'], 'thumbnail' );
}
protected function content_template() {
?>
<img src="{{{ settings.image.url }}}">
<?php
}
}