How to update widget from widget() function?

I’m trying to create a simple linkroll widget for displaying recent https://pinboard.in links via their API. To maximize loading speed, I want to cache the linklist in a widget field, as well as the timestamp when it was fetched last.

Now, if a defined time is over, I want to reload the link list via cURL and save it again in the widget field. How to do this from outside of the update() function?

My code:

// display widget
function widget($args, $instance) {

    extract( $args );

    // get widget title
    $title          = apply_filters('widget_title', $instance['title']);

    //  get options
    $token          = $instance['token'];
    $tags           = $instance['tags'];
    $unread         = $instance['unread'];
    $range          = $instance['range'];

    // update linklist based on cache validity
    $isvalid = $this->_check_valid_cache( $instance['expires'], $range );
    if ( $isvalid === TRUE ) {
        $cache         = $instance['cache'];
        $expires       = $instance['expires'];
    } else {
        $cache         = $this->_get_recent( $token );
        $expires       = $isvalid;
        /* --> does not work!! */
        $this->update($instance, $instance);
    }
    /* ...display widget... */

}

1 Answer
1

Huh. It had never actually occurred to me to use widget instance as cache. I hadn’t ever seen such implementation either.

This is quite an original idea, and as such it is hard to accurately point out benefits and issues with implementation. For starters update() doesn’t actually save anything, it just used as check for actual save and I won’t say where saving even happens from quick look because it’s abstracted deeper.

From my experience the more traditional implementation would be to cache using more conventional approach (such as transients) and tie it to API, not to widget.

As argument for that imagine user puts two different instances of widget in two different sidebars, but configures them the same way. They will be polling API at double rate, while they actually need exactly same data from API and could (and should) share it.

Leave a Comment