Pass the same object to multiple widgets in a template with one query

I am currently looking into passing a single query into multiple widgets on a template without running multiple queries. The obvious goal is speed and efficiency.

I have a widget that will deliver specific aspects of the same object with different instances of the widget in the template. Widget instances are a must, but the object instance should remain unchanged. Is there a sweet spot in the template run of actions and filters I should look for in my widget?

For example, I want object->title to show in my widget at the top of the page, so I check that box and so to show in that area. Then I have another instance of the widget where I check object->content to show in that area.

That’s very easy inside of the widget, however, very inefficient because I just ran two queries for the same object, because of my widgets being two different objects unto themselves.

How can my widget not attempt the same query twice in this situation? Will get_queried_object run a query for both of those widget instances?

2 Answers
2

I suggest to use the Object Cache API or Transients API, whatever fits better your needs.

A very quick example with object cache:

// helper function
function get_my_object() {
    $object = wp_cache_get( 'my_object' );
    if ( false === $object ) {
        $args = array( .... );
        $object = new WP_Query( $args );
        wp_cache_set( 'my_object', $object );
    } 
    return $object;
}

class cyb_my_widget extends WP_Widget {

    function __construct() {
        // ...
    }

    function widget( $args, $instance ) {
        // ...
        $object = get_my_object();
    }

    function update( $new_instance, $old_instance ) {
        // ...
    }

    function form( $instance ) {
       // ...
    }
}

Leave a Comment