Last active
August 1, 2021 00:14
-
-
Save pingram3541/62f3440f88ba01462c0be096ea5d649e to your computer and use it in GitHub Desktop.
Elementor HTML Widget - Add toggle to render script in wp_footer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Modify HTML Widget to load as an inline script in wp_footer | |
* | |
* 1) Add toggle control to html widget for loading as a footer script | |
* with jQuery dependency | |
* | |
* 2) Use 'elementor/frontend/widget/should_render' filter to disable the html widget's | |
* normal output on the front end and add our script to the wp_footer action using the | |
* global variable: $html_custom_script | |
* | |
**/ | |
//part 1. to add our toggle control | |
add_action( 'elementor/element/html/section_title/before_section_end', function( $element, $args ) { | |
/** @var \Elementor\Element_Base $element */ | |
$element->add_control( | |
'render_script', | |
[ | |
'type' => \Elementor\Controls_Manager::SWITCHER, | |
'label' => __( 'Render as Footer Script', 'elementor' ), | |
'label_on' => __( 'Enable', 'elementor' ), | |
'label_off' => __( 'Disable', 'elementor' ), | |
'return_value' => 'yes', | |
'default' => 'no', | |
] | |
); | |
}, 10, 2 ); | |
//part 2. filter to kill render and load inline script | |
add_filter( 'elementor/frontend/widget/should_render', function( $bool, $element ){ | |
if ( 'html' === $element->get_name() ) { | |
$settings = $element->get_settings(); | |
if( 'yes' === $settings['render_script'] ){ | |
global $html_custom_script; | |
$html_custom_script = do_shortcode( $settings['html'] ); | |
if ( ! wp_script_is( 'jquery', 'done' ) ) { | |
wp_enqueue_script( 'jquery' ); | |
} | |
add_action( 'wp_footer', function(){ | |
global $html_custom_script; | |
echo $html_custom_script; | |
}, 99999 ); | |
return false; | |
} else { | |
return true; | |
} | |
} else { | |
return true; | |
} | |
}, 10, 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment