Strategies for maximizing cache efficiency with Field Forge.
When to Use PostMeta Sync
If third-party plugins require field values in wp_postmeta:
php
add_action( 'fieldforge/value_updated', function( $post_id, $field_name ) {
$sync_fields = [ 'price', 'sale_price', 'sku', 'stock_quantity' ];
if ( in_array( $field_name, $sync_fields, true ) ) {
$value = FIELDFORGE_Field_Values::instance()->get_value( $field_name, $post_id );
update_post_meta( $post_id, '_' . $field_name, $value );
}
}, 10, 2 );Cache Invalidation
Caches are automatically invalidated when:
- A field value is updated (
fieldforge/value_updatedaction) - All values for a post are deleted (
fieldforge/values_deletedaction) - A field group is saved or deleted
Avoiding N+1 Queries
php
// Bad: N+1 queries
$ids = [1, 2, 3, 4, 5];
foreach ( $ids as $id ) {
$price = get_field( 'price', $id ); // 1 query each = 5 queries
}
// Good: Preload then access
fieldforge_preload( $ids );
foreach ( $ids as $id ) {
$price = get_field( 'price', $id ); // 0 queries (all from cache)
}Transient Caching for Expensive Operations
php
function get_featured_products_data() {
$cache_key = 'featured_products_data';
$data = get_transient( $cache_key );
if ( false === $data ) {
$query = new WP_Query( [
'post_type' => 'product',
'posts_per_page' => 6,
'meta_key' => '_is_featured',
'meta_value' => '1',
] );
fieldforge_preload( wp_list_pluck( $query->posts, 'ID' ) );
$data = [];
while ( $query->have_posts() ) : $query->the_post();
$data[] = [
'title' => get_the_title(),
'price' => get_field( 'price' ),
'image' => get_field( 'thumbnail' ),
'url' => get_permalink(),
];
endwhile;
wp_reset_postdata();
set_transient( $cache_key, $data, HOUR_IN_SECONDS );
}
return $data;
}
// Invalidate when product fields change
add_action( 'fieldforge/value_updated', function( $post_id ) {
if ( get_post_type( $post_id ) === 'product' ) {
delete_transient( 'featured_products_data' );
}
}, 10, 1 );—