I have a widget that I have been working on, that contains a <script>
tag inside the $widget->form()
method. I use the following in my source code, within the script tag:
<script>
(function ($) {
var desrdPostTypeSelector = '#<?php echo $this->get_field_id( 'desired_post_type' ); ?>';
var beginPostTypeSelector = '#<?php echo $this->get_field_id( 'beginning_post_type' ); ?>';
$('#<?php echo $this->get_field_id( 'isSingle' ); ?>').on( 'change', function() {
$( '.<?php echo $multi_post_class ?>, #<?php echo $beginning_post_tag_id ?>' ).toggleClass('hidden', this.checked);
});
$('#<?php echo $this->get_field_id( 'isTaxonomy' ); ?>').on( 'change', function() {
$( '#<?php echo $beginning_post_tag_id ?>' ).toggleClass('hidden', this.checked);
});
$('#<?php echo $this->get_field_id( 'isSingle' ); ?>, #<?php echo $this->get_field_id( 'isTaxonomy' ); ?>').on( 'change', function () {
if ( $('#<?php echo $beginning_post_tag_id ?>').hasClass('hidden') ) {
clearAllDisabledBy( getListOfOptionElements( $( desrdPostTypeSelector )[0] ) );
} else {
disableOptionsBasedOnSelected( $( beginPostTypeSelector )[0], $( desrdPostTypeSelector )[0] );
}
} );
$('#<?php echo $this->get_field_id( 'beginning_post_type' ); ?>').on( 'change submit', function () {
clearAllDisabledBy( getListOfOptionElements( $( desrdPostTypeSelector )[0] ) );
disableOptionsBasedOnSelected( this, $( desrdPostTypeSelector )[0] );
} );
})(jQuery);
</script>
Then, when I go to Appearance -> Widgets
and I copy my widget over to a sidebar none of the JavaScript works! I looked at the rendered HTML and saw this:
Why is the unrendered widget number __i__
showing up in the JavaScript but not in the HTML portion? This is a fresh drag-and-drop instance of the widget, mind you, no page refresh. However, when I refresh the page, everything works fine. Am I doing something wrong here?
The file where the JavaScript functions are located is being included in the Sources list in dev tools, I can also see it in the HTML, but for kicks here's how I enqueue that:
In plugin file:
function enqueue_scripts() {
wp_enqueue_script(
'related_posts_script_helpers',
plugin_dir_url( __FILE__ ) . "assets/related-posts-script-helpers.js",
array( 'jquery' ),
'1.0'
);
}
if ( is_admin() ) {
add_action( 'admin_enqueue_scripts', 'enqueue_scripts' );
}
Is this is a timing issue (on my part) or a bug in WordPress? Any help would be much appreciated. Thank you!