[wp-trac] [WordPress Trac] #32474: Facilitate widgets to be stored in posts instead of options

WordPress Trac noreply at wordpress.org
Wed May 27 18:22:43 UTC 2015


#32474: Facilitate widgets to be stored in posts instead of options
------------------------------+--------------------------
 Reporter:  westonruter       |       Owner:  westonruter
     Type:  enhancement       |      Status:  closed
 Priority:  normal            |   Milestone:  4.3
Component:  Widgets           |     Version:  2.8
 Severity:  normal            |  Resolution:  fixed
 Keywords:  has-patch commit  |     Focuses:
------------------------------+--------------------------

Comment (by westonruter):

 Replying to [comment:13 Stagger Lee]:
 > Does it mean cache plugins would be able to refresh widgets data when
 post changed more easy ?

 Well, this provides another way to flush a widget cache via the
 `save_post` action. But you can still do this now in Core just inside of
 the widget's `update()` callback anyway. But here's how you can do it with
 a `save_post` action (untested):

 {{{#!php
 <?php

 /**
  * Caching depends on the Customize Widgets Plus plugin's Widget Posts
 module.
  * @Link https://github.com/xwp/wp-customize-widgets-plus/pull/12
  */
 class Foo_Widget extends WP_Widget {

         function __construct() {
                 parent::__construct( 'foo', 'Foo' );
                 if ( post_type_exists( 'widget_instance' ) ) {
                         add_action( 'save_post_widget_instance', array(
 $this, 'flush_output_cache' ) );
                 }
         }

         function flush_output_cache( $post_id ) {
                 $post = get_post( $post_id );
                 if ( ! empty( $post ) ) {
                         // Note that a widget_instance's post_name is the
 widget_id.
                         wp_cache_delete( $post->post_name, 'widget_output'
 );
                 }
         }

         function widget( $args, $instance ) {
                 if ( post_type_exists( 'widget_instance' ) ) {
                         $cached = wp_cache_get( $this->id, 'widget_output'
 );
                         if ( false !== $cached ) {
                                 echo $cached;
                                 return;
                         }
                         ob_start();
                 }

                 // ...

                 if ( post_type_exists( 'widget_instance' ) ) {
                         $content = ob_get_contents();
                         wp_cache_set( $this->id, $content, 'widget_output'
 );
                         ob_flush();
                 }
         }
 }

 }}}

--
Ticket URL: <https://core.trac.wordpress.org/ticket/32474#comment:14>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list