9

I have tried doing some research on this but haven't found anything solid yet. I have a plugin I am working on and between the last version and the new version we made some updates to the widget that changes some of the settings names (on the backend) and I am having trouble creating an upgrade routine to do this.

What I have done so far that seems to (mostly) work is this:

$widget = get_option( 'widget_name' );

if( is_array( $widget ) && ! empty( $widget ) ) {
    foreach( $widget as $a => $b ) {
        if( ! is_array( $b ) ) {
            continue;
        } 

        foreach( $b as $k => $v ) {
            $widget[$a]['setting1'] = $widget[$a]['oldsetting1'];
            $widget[$a]['setting2'] = $widget[$a]['oldsetting2'];
        }
    }

    update_option( 'widget_name', $widget );
}

In most of my tests this works out ok, but the problem becomes that the old widget no longer displays it's output. Only the title of the widget will show. I can fix this by going and saving each individual widget and then it will work fine, but I don't want to make my users do that.

I thought something like this might work:

$settings = $widgets->get_settings();

foreach( $settings as $s ) {

    $s['setting1'] = $s['oldsetting1'];
    $s['setting2'] = $s['oldsetting2'];

    $widgets->save_settings( $s );

}

But it seems that the save_settings() call must be wrong because this removes the widget entirely.

I am having trouble finding any sort of standard for something like this and would just like to hear any thoughs, ideas, or links you might have to doing something like this.

Thanks in advance for any help.

EDIT:

This is not actually a question about tracking license keys or upgrading plugins that aren't hosted on the WP repo. What this is more about is updating settings between 2 version of a plugin when a user upgrades.

Example:

version 1.0.0 has a setting field name

Well in version 1.1.0 we decide we need both first and last name so we change the old setting to be first_name and then add a new setting last_name.

Transferring these options if saved as post meta for a custom post type is no problem:

$old_name = get_post_meta( $post->ID, 'name', true );
$first_name = update_post_meta ( $post->ID, 'first_name', true );
delete_post_meta( $post->ID, 'name' );

So that part is easy. What I am having trouble with that seems to not be easy is doing this same thing but for WIDGET settings.

Hopefully this will clear up any confusion and help to make this be easier to answer.

EDIT 2:

Result of echo '<pre>' . print_r( $widget, true ) . '</pre>'; from first code chunk above:

Array
(
[2] => Array
    (
        [title] => Class Schedule
        [id] => 23
        [display_type] => grid
        [order] => asc
        [display_title_text] => Events on
        [paging] => 1
        [list_max_num] => 7
        [list_max_length] => days
        [list_start_offset_num] => 0
        [list_start_offset_direction] => back
        [gce_per_page_num] => 7
        [gce_events_per_page] => days
    )

[3] => Array
    (
        [title] => Examples
        [id] => 24
        [display_type] => grid
        [order] => asc
        [display_title_text] => Events on
        [paging] => 1
        [list_max_num] => 7
        [list_max_length] => days
        [list_start_offset_num] => 0
        [list_start_offset_direction] => back
        [gce_per_page_num] => 7
        [gce_events_per_page] => days
    )

[_multiwidget] => 1
)
  • I just saw this article today on Tutsplus, I haven't even read it all, but it seems to be up your ally. Create a License Controlled Theme and Plugin Update System – OnethingSimple Feb 11 '15 at 0:56
  • @OnethingSimple Thanks for the reply but that doesn't quite look like what I am going for. I will update the question to make it more clear. – Nick Young Feb 11 '15 at 1:12
  • Any chance we could get a dump of what the widget settings structure looks like that you are reading in (even if you have to change some of the values). That might help give an idea of what is going wrong. e.g. echo "<pre>" . print_r($widget, true) . "</pre>"; – Privateer Feb 11 '15 at 3:08
  • @Privateer Appended to the bottom of the OP now. – Nick Young Feb 12 '15 at 18:12
3
+100

I've did a quick test on just changing the option and it seems to work.

What I did is:

  1. Wrote a widget that has just 2 fields: "Title" and "Name". Add several instances of this widget to my sidebars. Been sure that they are shown correctly in frontend.
  2. Edited the class to use 3 fields: "Title" and "First Name" (to replace "Name") and added "Last Name".
  3. Edited the function that register the widget on 'widgets_init' to call a function that update the widget options:

    add_action( 'widgets_init', 'my_example_widget_register' );
    
    function my_example_widget_register() {
    
      $widget_name = 'my_example_widget';  // <-- You will probably replace this
    
      $options = get_option("widget_{$widget_name}");
    
      // if the widget is not updated, run a function that updates it
      if ($options && ! get_option("is_{$widget_name}_updated")) {
          // use class below to update options
          $updater = new MyExampleWidgetUpdater($widget_name, $options);
          $updater->update();
      }
    
      register_widget('My_Example_Widget'); // <-- You will probably replace this
    }
    
  4. Wrote a simple class to update widget options:

    class MyExampleWidgetUpdater
    {
    
      private $name;
      private $options;
    
      public function __construct($name, $options) {
         $this->name = $name;
         $this->options = $options;
      }
    
      public function update() {
        // loop all the options
        array_walk($this->options, function(&$option, $key) {
            if (is_array($option) && is_numeric($key)) {
              $option = $this->getOption($option);
            }
        });
        // update all options in DB
        update_option("widget_{$this->name}", $this->options);
        // set the widget as updated
        update_option("is_{$this->name}_updated", 1);
      }
    
      private function getOption($options) {
        if (!isset($options['name'])) {
           return $options;
        }
        $options['first_name'] = $options['name'];
        $options['last_name'] = '';
        unset($options['name']);
        return $options;
      }
    }
    
  5. I edited the widget class to save the option "is_{$widget_name}_updated" inside the update() method, in this way the updater class will never be called for new users that never installed old widget

    class My_Example_Widget {
    
        ...
    
        public function update($new_instance, $old_instance) {
            ...
    
            $widget_name = 'my_example_widget';
            update_option("is_{$widget_name}_updated", 1);
        }
    }
    
  6. I visited my site and the widgets saved with old options are displayed with no issue using new options. (Of course "last name" is always empty).

A good idea may be replace the "is_{$widget_name}_updated" option, with an option that store the actual version of the widget, in this way it will be handy next time you need an update.

  • SO looking through your answer without testing it just yet. It seems similar to what I have done with just using update_option correct? I am wondering now if the hook matters maybe? I am hooking it to the init hook. Is there a huge difference by adding it to the widgets_init hook instead? I was pretty sure they fire off at the same time. Thanks for your help. – Nick Young Feb 12 '15 at 18:15
  • @NickYoung There's no difference in the hook. But in your first code snippet (that's the one similar to the mine) the second (inner) foreach is wrong. – gmazzap Feb 12 '15 at 21:16
  • I just got a chance to implement the code you wrote up. It works great, but I am still getting the same problem as I was getting before. It transfers the options successfully, but after running the upgrade routine for the plugin the widget stops outputting it's main HTML and only shows the title of the widget. If I go to widget settings and simply just click the save button then it pops up again. Any thoughts? – Nick Young Feb 12 '15 at 21:41
  • To add to my last comment. Its like the options are being updated correctly but the actual instance isn't. Is that even a possibility? – Nick Young Feb 12 '15 at 21:48
  • Nope disabled all caching. Also tested on 2 different hosts with the same problem. – Nick Young Feb 12 '15 at 22:29
1

Just to weigh in from a different angle - rather than auto-upgrade all settings on plugin update, simply check for an "old" setting & map to "new" settings on-the-fly:

function widget( $args, $instance ) {
    if ( isset( $instance['old_setting'] ) )
         $instance = self::_version_compat( $instance );
}

static function _version_compat( $instance ) {
    $instance['new_setting'] = $instance['old_setting'];
    // etc.

    return $instance;
}
0

Off the top of my head, each instance of a widget is given some sort of unique ID. I want to say that becomes a prexfix to the keys for the widget.

I remember poking at this some time ago but can't remember what the exacts were, sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.