Back to Snippets

Transient Cache for Expensive Queries

PHP Performance April 6, 2026

Cache expensive WP_Query results with transients and auto-flush on post save. Includes cache key strategy for different query variations.

Snippet Stats

Lines 38
Characters 1,031
Read 2 mins
php • 38 lines
/**
 * Get featured products with transient caching.
 *
 * @param int $count Number of products to return.
 * @return array
 */
function mytheme_get_featured_products( int $count = 6 ): array {
    $cache_key = 'mytheme_featured_products_' . $count;
    $products  = get_transient( $cache_key );

    if ( false !== $products ) {
        return $products;
    }

    $query = new WP_Query( array(
        'post_type'      => 'product',
        'posts_per_page' => $count,
        'meta_key'       => '_featured',
        'meta_value'     => 'yes',
        'no_found_rows'  => true,
        'fields'         => 'ids',
    ) );

    $products = $query->posts;
    set_transient( $cache_key, $products, 12 * HOUR_IN_SECONDS );

    return $products;
}

/**
 * Flush the cache when a product is saved.
 */
add_action( 'save_post_product', function( int $post_id ): void {
    // Delete all cached variations.
    foreach ( array( 3, 6, 9, 12 ) as $count ) {
        delete_transient( 'mytheme_featured_products_' . $count );
    }
} );

Found an issue with this snippet? Help us improve by reporting it. Report it →

Related Snippets

View all
JavaScript
This code snippet demonstrates how to optimize React performance by utilizing memoization and callbacks, which is particularly useful when dealing wit...

React Performance Optimization Using Memoization And Callbacks

JavaScript
This React code snippet utilizes memoization to enhance performance in complex, data-intensive components that require frequent re-renders. It showcas...

Optimizing React Component Performance With Memoization Techniques

JavaScript
This React snippet demonstrates optimization techniques using memo and useCallback hooks, ideal for complex components with frequent re-renders. It sh...

Optimizing React Performance With Memo And UseCallback Hooks