I’m having a problem with my custom WordPress Widget I’m making. For some weird reason the form function gets ran twice, and thus, makes two Redactor textareas, but it only happends when I add the widget to a sidebar. Not when I click the save button after it has been added.
How can I do so my form function only gets ran once, or at least make the JavaScript run once.
Full widget code
My form function
function form($instance)
{
$instance = wp_parse_args((array) $instance, array( 'box1' => '', 'box2' => '', 'box3' => '', 'box4' => '' ));
$box1 = $instance['box1'];
$box2 = $instance['box2'];
$box3 = $instance['box3'];
$box4 = $instance['box4'];
$boxqty = $instance['boxqty'];
$uniqueID = rand();
echo "Unique ID: ".$uniqueID;
?>
<p>
<label for="<?php echo $this->get_field_id('boxqty'); ?>">Number of blocks: (1-4)
<input class="widefat" id="<?php echo $this->get_field_id('boxqty'); ?>" name="<?php echo $this->get_field_name('boxqty'); ?>" type="text" value="<?php echo attribute_escape($boxqty); ?>" />
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('box1'); ?>">Box 1:
<textarea class="widefat redactor_content_<?php echo $uniqueID; ?>" id="box1" name="<?php echo $this->get_field_name('box1'); ?>" style="width: 600px;"><?php echo $box1; ?></textarea>
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('box2'); ?>">Box 2:
<textarea class="widefat redactor_content_<?php echo $uniqueID; ?>" id="<?php echo $this->get_field_id('box2'); ?>" name="<?php echo $this->get_field_name('box2'); ?>" style="width: 600px;"><?php echo $box2; ?></textarea>
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('box3'); ?>">Box 3:
<textarea class="widefat redactor_content_<?php echo $uniqueID; ?>" id="<?php echo $this->get_field_id('box3'); ?>" name="<?php echo $this->get_field_name('box3'); ?>" style="width: 600px;"><?php echo $box3; ?></textarea>
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('box4'); ?>">Box 4:
<textarea class="widefat redactor_content_<?php echo $uniqueID; ?>" id="<?php echo $this->get_field_id('box4'); ?>" name="<?php echo $this->get_field_name('box4'); ?>" style="width: 600px;"><?php echo $box4; ?></textarea>
</label>
</p>
<!--Activate Redactor-->
<script type="text/javascript">
jQuery('.redactor_content_<?php echo $uniqueID; ?>').redactor({
fixed: true
});
console.log('Unique ID: <?php echo $uniqueID; ?>');
</script>
<?php
}
I tested some things and what seems to be happening is that the whole widget loads both on the left, where the widget form content is hidden, and on the right in the ‘active’ widgets sections. Untested, but you should be able to target the ‘active’ section only with:
If I had the complete widget I might be able to spot something else.