PHP - Wordpress - Plugin Widget Update Function -

2019-04-12 05:49发布

问题:

i am in the process of developing a wordpress plugin with a widget. Currently the update function for the widget looks like this.

function update($new, $old){
    $instance = $old;
    //Update Values
    $instance['element-one'] = $new['element-one'];
    $instance['element-two'] = $new['element-two'];
    $instance['element-three'] = $new['element-three'];
    $instance['element-four'] = $new['element-four'];
    //Return New Instance
    return $instance;

and this works as it is supposed to. But i have a long list of elements and for the sake of cleanliness of code i am trying to achieve them with a simple function as follows:

function update($new, $old){
    $instance = $old;
    //Update Values
    foreach($instance as $k => $v){
        $instance[$k] = $new[$k];
    }
    //Return New Instance
    return $instance;

Though this doesn't seem to work. The Widget values are not being updated if i use this function. So just to test if it works the way i want it to... i wrote a sample script which is working fine. The script is as follows.

$a = array(
  'a' => '1',
  'b' => '2',
  'c' => '3'
);

$b = array(
  'a' => 'A',
  'b' => 'B',
  'c' => 'C'
);

function swap_values($old, $new){
  $result = $old;
  foreach($result as $k => $v){
    $result[$k] = $new[$k];
  }
  return $result;
}

$res = swap_values($a, $b);
var_dump($res);

This script is working fine and it swaps the values of the arrays but it seems for some reason this is not doing well in wordpress.

Another Few strange things that i realized while working on this is

  • if suppose i have a few elements declared in the $instance array in the form function of the widget and the update function is updating them like $instance['old'] = $instance['new']; it works fine. Also if i have the plugin installed and activated and then i change the update function to use the foreach loop they work fine.
  • But Then after i have changed the update function to use foreach loop if i add anymore elements to the $instance array they are not being updated, whereas previously declared elements are.
  • Also if i install and activate this plugin [after updating the update function to use foreach loop] on a separate wordpress installation none of the elements seem to update.

I am sure there is something very minor that i am missing. Any help or suggestions from you would be greatly appreciated.

回答1:

I have found a simple solution: do not include an update function in your extension of the widget.

The core simply returns the $new_instance variable as a default (wp-includes/widgets.php):

function update($new_instance, $old_instance) {
    return $new_instance;
}

I have tested this with success in my own widget and have determined that making your own update function is useful for filtering user input, but it does not seem necessary.