1

I'm trying to prevent some images that are above the fold from being lazy loaded but I can't access the html of the images. Only the wrappers.

Is there any way to access plane HTML of Elementor Wordpress?

Thank you

3
  • To change the widget content or HTML you can use the Filter Hook elementor/widget/render_content or to add attributes you can try Action Hook elementor/frontend/before_render. Commented Dec 7, 2024 at 20:36
  • Nice! this seem to be what I was looking for. Can I target specific element in php? For example, I only wanna add lazyload="eager" to specific selector .theme-post-featured-image img Commented Dec 7, 2024 at 21:25
  • Yes, to add an attribute to img tag of the Image Widget, use elementor/widget/render_content hook. To get the image name use get_name() method Commented Dec 8, 2024 at 12:15

1 Answer 1

3

To add a custom attribute to a specific Image Widget`s IMG tag follow the steps given below:

For example, if you are required not to lazy load selected images and want to add the attribute loading="eager" to the IMG tag,

1. Add the class eager in the Advanced tab of the Edit widget to the Image Widget you do not want to lazy load. Check the screenshot given below:

enter image description here

2. Add the code given below in the child theme's functions.php file

add_action( 'elementor/widget/render_content', function( $content, $widget ) {
    if ( 'image' === $widget->get_name() ) {
        $settings = $widget->get_settings();
        $classes = $settings['_css_classes'];
        if ( strpos( $classes, 'eager' ) !== false ) {
            $content = str_replace( '<img', '<img loading="eager"', $content );
        }
    }
    return $content;
}, 10, 2 );
Sign up to request clarification or add additional context in comments.

8 Comments

Thank you, but this doesn't work. I added the class in elementor advanced settings and added the code to functions.php but there is still loading="lazy" on that image. Is it right, that the class "eager" is being added to the wrapper of img? It's 4 levels up from img
In my case, it is working fine. prnt.sc/361r7H9ZiO_L It would help if you tried to increase the priority value of the action hook in step 2.
I've added 99 priority but still doesn't help. prnt.sc/wXefhqBEhv2Q Maybe I got it nested too deep?
You should check the widget name using the $widget->get_name() line of code. Put this before the if statement echo $widget->get_name(); And see what the name of your widget is. And replace the name of the widget in the if statement. I hope you understand this
It just echoes "html"
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.