Insomnia88
Insomnia88

Reputation: 368

adding custom styles/scripts to elementor widget

I am currently struggling to inject a custom style to an existing elementor widget (no custom one).

Sure I could simply put the changes in a global .css but then I wouldn't profit from elementors dynamic component based includes.

I found some methods in the offical code reference but they doesn't seem to do what I want to achieve. For example elementor/editor/before_enqueue_styles which only affects the whole editor, same for frontend.

Upvotes: 0

Views: 1173

Answers (1)

SkullWritter
SkullWritter

Reputation: 11

use the following for dynamic styles and scripts on a widget:

class ReplaceMeClassName extends \Elementor\Widget_Base {
    public function __construct( $data = [], $args = null ) {
        parent::__construct( $data, $args );
        
        /** Main Style **/
        $src= 'the_source_with_complete_url.min.css';
        $version=filemtime( 'the_source_with_complete_path.min.css');
        if(WP_DEBUG===true){
            /** style **/
            $src= 'the_source_with_complete_url.css';
            $version=filemtime('the_source_with_complete_path.css');
        }
        /** style **/
        wp_register_style( 'name_of_the_style', $src, /* depends */ array(), $version );
        
        /** Main Script **/
        $src= 'the_source_with_complete_url.min.js';
        $version=filemtime( 'the_source_with_complete_path.min.js');
        if(WP_DEBUG===true){
            /** Script **/
            $src= 'the_source_with_complete_url.js';
            $version=filemtime('the_source_with_complete_path.js');
        }
        /** Script **/
        wp_register_script( 'name_of_the_script', $src, /* depends */ array(), $version );
    }
    /**
     * Enqueue when widget is on page.
     */
    public function get_style_depends() {
        return array( 'name_of_the_style' );
    }
    /**
     * Enqueue scripts when widget is on page.
     */
    public function get_script_depends() {
        return array( 'name_of_the_script' );
    }
    /* ..... */

Upvotes: 0

Related Questions