I developed a custom widget for the Elementor plugin called carousel slider. There I set elementor default setting field select2
for multiple select. I populate the Elementor Libray templates in that select2 field. Normally works fine. But I want to add newly created template which is created from editor preview iframe. And here the templates are created using ajax method which not loading the page.
To add the newly created item I used Elementor JS hook elementor.hooks.addAction( 'panel/open_editor/widget/widget-type
which is fired when any widget is going to be edited or editor of that widget-type is opened. Using jQuery ajax I managed to add the newly created template to that select2
field. But the problem is "When I first time click on that widget-type ( in my case carousel slider ) in preview iframe and opened the editor, the newly created template added and appears in select2 options value. Now I close that editor and again I open editor of my widget by clicking on carousel widget the new added template disappear. I can not figured out the problems. My codes are below..
(function( $ ) {
$(document).ready( function() {
elementor.hooks.addAction( 'panel/open_editor/widget/premium-carousel-widget', function( panel, model, view ) {
$.ajax({
url : template_update.ajax_url,
type : 'POST',
data : {
action : 'update_template',
whatever : 'yes'
},
success : function( data ) {
if( data !== '' ) {
console.log( data );
$('select[data-setting=premium_carousel_slider_content]').append( $(data ) );
}
console.log( 'hello' );
}
});
});
});
})(jQuery);
PHP codes are below. I used WordPress ajax API.
public function updating_template_after_save() {
if( $_POST['whatever'] ) {
$pagelist = get_posts(array(
'post_type' => 'elementor_library',
'showposts' => 999,
));
$options = array();
if ( ! empty( $pagelist ) && ! is_wp_error( $pagelist ) ){
foreach ( $pagelist as $post ) {
$options[ $post->ID ] = __( $post->post_title, 'premium_elemnetor' );
}
}
$old_items = get_option( 'temp_count' );
if( $old_items != $options ) {
$html = '';
$new_item = array_diff( $options, $old_items );
foreach( $new_item as $key => $value ) {
$html .= '<option value="'.$key.'">'. $value .'</option>';
}
echo $html;
update_option( 'temp_count', $options );
}
}
die();
}