1

I add a widget via Customizer. It's a simple widget, with basic loop, which displays 5 latest posts where each post have Featured Image. Because of the Featured Image, this widget run hundreds of queries, without Featured Image the number of queries returns back to normal.

It happens only when adding widgets and viewing the site via the Customizer, there is no such issue on the front end.

Also tested with the default WP "Recent Posts" widget with only one line added for each post after the "$show_date" if statement.

<?php the_post_thumbnail( 'thumbnail' ); ?>

Is it a known issue?

1

The issue boils down to this bit of code in WP_Widget::display_callback():

$was_cache_addition_suspended = wp_suspend_cache_addition();
if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
    wp_suspend_cache_addition( true );
}

This gets called right before WP_Widget_Recent_Posts::widget() and its purpose is to try as best as possible for back-compat to prevent widgets previewed in the Customizer from polluting the object cache prior to publishing the changes. In the case of the Recent Posts widget showing the featured image with each post, suspending the cache means that the postmeta for each post will potentially need to be queried and re-queried each time they are accessed in the customizer.

The workaround here to explicitly turn off the cache suspension when rendering your widget is to add the following to the beginning of your widget subclass's widget method:

if ( $this->is_preview() && wp_suspend_cache_addition() ) {
    wp_suspend_cache_addition( false );
}

This will immediately undo the cache addition suspension that was just in the invoking WP_Widget::display_callback() method, and the number of queries should return to what you see on the frontend.

  • Hi Weston, thank you. It's definitely changes the queries amount. Does suspending the cache in this case have any negative affects on the performance and behavior of the customizer and everything else within the whole environment or it's pretty much safe? – Vasili Apr 2 '17 at 10:27
  • The cache suspension is not needed in the case of the Recent Posts widget because there is nothing bring cached which is customized. Now, if the HTML output of the widget were cached, then suspension wild be needed to prevent cache pollution. But not in this case. There are some improvements needed to the widgets in core to better accommodate caching and the customizer to eliminate the workaround in my answer. – Weston Ruter Apr 2 '17 at 18:04

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.