wpsmith / genesis-sandbox-featured-content-widget

Genesis Sandbox Featured Content Widget. Based on Nick Croft's Genesis Featured Widget Amplified for additional functionality which allows support for custom post types, taxonomies, and extends the flexibility of the widget via action hooks to allow the elements to be re-positioned or other elements to be added.
39 stars 21 forks source link

Still generating a lot of get_term_by queries #12

Closed jb510 closed 10 years ago

jb510 commented 10 years ago

I'm thinking get_term_by (used for do_more_from_category() on widget.php:650 ) should perhaps be cached.

Found this https://github.com/Automattic/Edit-Flow/pull/235 which seems like a useful example.

Is it worth writing a caching wrapper function for get_term_by like they did? I might give repurposing their code a go for this to see if it helps.

jb510 commented 10 years ago

Ok, perhaps cleaner, I'm trying something based of VIP's cached get_term_by. Not getting the result I was hoping for yet.

function wpcom_vip_get_term_by( $field, $value, $taxonomy, $output = OBJECT, $filter = 'raw' ) {
    // ID lookups are cached
    if ( 'id' == $field )
        return get_term_by( $field, $value, $taxonomy, $output, $filter );

    $cache_key = $field . '_' . md5( $value );
    $term_id = wp_cache_get( $cache_key, 'get_term_by' );

    if ( false === $term_id ) {
        $term = get_term_by( $field, $value, $taxonomy );
        if ( $term && ! is_wp_error( $term ) )
            wp_cache_set( $cache_key, $term->term_id, 'get_term_by' );
        else
            wp_cache_set( $cache_key, 0, 'get_term_by' ); // if we get an invalid value, let's cache it anyway
    } else {
        $term = get_term( $term_id, $taxonomy, $output, $filter );
    }

    if ( is_wp_error( $term ) )
        $term = false;

    return $term;
}
jb510 commented 10 years ago

Cool. Looks like it's working