How to pass JavaScript variable to PHP in wordpress widget?

I found an easy way to pass a JavaScript variable to PHP variable. Please note that this method works in WordPress version 4.7.2, and only specifically on Widget. I wrote a lot of comments to try to explain what each line did. If you have a better solution, please share with us!

Solution:

  • Create a hidden input field to store the value of the javascript you want to pass.
  • Access that hidden input field and assign its value to a PHP variable.

Demo Widget:

  • I create a demo widget that add “LOVE YOU” word according to how many time you press the “Add LOVE YOU” button.

  • Note that I left the hidden field shown for better understanding.

  • You can change type="text" totype="hidden" to hide it.

  • This demo only focuses on the form function of the widget.

  • Make sure the click Save button, else the value of the hidden input is not saved by the widget.

Demo Widget ScreenShot:

enter image description here

Source code:

wp-text-repeater.php

<?php
/**
*Plugin Name: WP Text Reapter
**/

class wp_text_repeater extends WP_Widget {

    /**
     * Sets up the widgets name etc
     */
    public function __construct() {
        $widget_ops = array(
            'classname' => 'wp_text_repeater',
            'description' => 'Widget that prints LOVE YOU repeatedly according to button press',
        );
        parent::__construct( 'wp_text_repeater', 'WP Text Repeater Widget', $widget_ops );
    }

    /**
     * Outputs the content of the widget
     *
     * @param array $args
     * @param array $instance
     */
    public function widget( $args, $instance ) {
        // outputs the content of the widget
    $wp_text_repeater_button = ! empty( $instance['wp_text_repeater_button'] ) ? $instance['wp_text_repeater_button'] : '';
    $wp_text_repeater_appendee = ! empty( $instance['wp_text_repeater_appendee'] ) ? $instance['wp_text_repeater_appendee'] : '';
    $wp_text_repeater_hidden = ! empty( $instance['wp_text_repeater_hidden'] ) ? $instance['wp_text_repeater_hidden'] : '';
    }

    /**
     * Outputs the options form on admin
     *
     * @param array $instance The widget options
     */
    public function form( $instance ) {
        // outputs the options form on admin
    $instance = wp_parse_args( (array) $instance, array( 'wp_text_repeater_button' => '', 'wp_text_repeater_appendee' => '', 'wp_text_repeater_hidden' => ''));

    $wp_text_repeater_button = $instance['wp_text_repeater_button'];
    $wp_text_repeater_appendee = $instance['wp_text_repeater_appendee'];
    $wp_text_repeater_hidden = $instance['wp_text_repeater_hidden'];

    $tempHidden = 'wp_text_repeater_hidden';

  ?>
    <!-- Hidden field that store number of time user press the button -->
    <input
          class="widefat"
          id="<?php echo $this->get_field_id($tempHidden); ?>"
          name="<?php echo $this->get_field_name($tempHidden); ?>"
          type="text"
          value="<?php echo esc_attr($$tempHidden);?>"/>
  <?php

    $max = 0; //Number of time user press the button

    //if JavaScript front-end hidden input has value, assign $max to it.
    //This If statement sync between the javascript and the php part.
    if(strlen($$tempHidden) > 0){
      $max = intval($$tempHidden);
    }

    $counter = 0;
    while($counter < $max){ //loop according to how many time user press the button
  ?>
      <p>LOVE YOU!</p>
  <?php
     $counter++;
    }

    $id_prefix = $this->get_field_id(''); //get the widget prefix id.
  ?>
    <!-- You can append all your content herev-->
    <span id="<?php echo $this->get_field_id('wp_text_repeater_appendee')?>"></span>

    <!-- Add button that call jQery function to add "LOVE YOU" word -->
    <input style="background-color: #08a538; color:white; height: 27px;"
          class="button widefat"
          type="button"
          id="<?php echo $this->get_field_id('wp_text_repeater_button'); ?>"
          value="Add LOVE YOU"
          onclick="text_repeater.addLove('<?php echo $this->id;?>', '<?php echo $id_prefix;?>'); return false;"
          />

    <script>

    jQuery(document).ready(function($){
      var preIndexID;
      var numberOfLove = <?php echo $max; ?>; //grab value from the php in order to sync between the front and back end.
      text_repeater = {
          addLove :function(widget_id, widget_id_string){
              preIndexID = widget_id_string; //get the correct pre-index of the widget.
              numberOfLove++;
              numberOfLove = numberOfLove.toString(); //convert int to string for the hidden input field.
              $("#" + preIndexID + "wp_text_repeater_hidden").val(numberOfLove); //change the value of the hidden input field.
              $("#" + preIndexID + "wp_text_repeater_appendee").append('<p>LOVE YOU!</p>'); //live update the front-end with "LOVE YOU".
          }
      }
    });

    </script>
  <?php
    }

    /**
     * Processing widget options on save
     *
     * @param array $new_instance The new options
     * @param array $old_instance The previous options
     */
    public function update( $new_instance, $old_instance ) {
        // processes widget options to be saved
    $instance = $old_instance;

    $instance['wp_text_repeater_button'] = sanitize_text_field($new_instance['wp_text_repeater_button']);
    $instance['wp_text_repeater_appendee'] = sanitize_text_field ($new_instance['wp_text_repeater_appendee']);
    $instance['wp_text_repeater_hidden'] = sanitize_text_field( $new_instance['wp_text_repeater_hidden'] );

    return $instance;

    }
}

// register wp_text_repeater widget
function register_wp_text_repeater_widget() {
    register_widget( 'wp_text_repeater' );
}
add_action( 'widgets_init', 'register_wp_text_repeater_widget' );

Leave a Comment