This code snippet demonstrates how to optimize React performance by utilizing memoization and callbacks, which is particularly useful when dealing wit...
Back to Snippets
php
• 38 lines
JavaScript
JavaScript
JavaScript
Transient Cache for Expensive Queries
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
/**
* 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 allThis React code snippet utilizes memoization to enhance performance in complex, data-intensive components that require frequent re-renders. It showcas...
This React snippet demonstrates optimization techniques using memo and useCallback hooks, ideal for complex components with frequent re-renders. It sh...