I’ve tried doing this one of two ways:
-
In the
form
method of myWidget
class (which extendsWP_Widget
), I have the following snippet, which sets a global javascript variable:if( $instance ) : ?> <script type="text/javascript"> window.widget_order_name = "<?php echo $this->get_field_name( 'order' ) ?>"; </script> <?php endif;
-
In the widget admin markup, I also tried to create the following html structure:
<div field_name='<?php echo $this->get_field_name( 'order' ) ?>' id='order_field_name' class='hidden'> </div>
In my widget admin javascript file, I grab the value of this field_name in one of two ways (as seen below) and then attached that widget name to that of a hidden input field (which contains a value I want to store).
-
The first way, using
window.widget_order_name
:var widget_field_name = window.widget_order_name;
-
The second way, using
jQuery
to grab thefield_name
:var widget_field_name = $( '#order_field_name' ).attr( 'field_name' );
My problem:
Whenever I first move the widget from the Available Widgets container to my sidebar, I don’t get the actual field name, I get instead a sort of placeholder for the field name.
So, instead of getting something like this:
<input
type="hidden"
name="widget-hours-widget[2][order][]"
value="L48">
I get this:
<input
type="hidden"
name="widget-hours-widget[__i__][order][]"
value="L26">
After the save button is clicked, the field_name
gives me the correct name of the widget, widget-hours-widget[2]
rather than the placeholder widget-hours-widget[__i__]
.
Has anybody run into a similar problem or know how to go about fixing it?
Thanks.
The Problem
So I figured out what the problem was. In the statement below, jQuery was grabbing the first element with the id of
#order_field_name
.As it turns out, there were actually two elements with that id. The first element with this id is the widget in the Available Widgets section. This is the section where you click & drag the widget to a sidebar. This is element the jQuery selector was returning to me.
And the markup:
The Solution
I had a click listener that was dynamically adding hidden input boxes with the field name.
So, I used jQuery’s tree traversal methods to go back up to widget’s
form
element and traverse back down to the element with the#order_field_name
id. From there, I grabbed thefield_name
attribute, which has the correctfield_name
.From there, I used a bit of javascript & jQuery to create a hidden input element with the desired attribute, which looks something similar to this: