Skip to content

Instantly share code, notes, and snippets.

@rheinardkorf
Created May 26, 2021 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rheinardkorf/1035297fc071acc081c1d6cbacacccbb to your computer and use it in GitHub Desktop.
Save rheinardkorf/1035297fc071acc081c1d6cbacacccbb to your computer and use it in GitHub Desktop.
acf-hooks-basic.php
<?php
/**
* Hook before acf_get_value() queries the DB.
*/
add_filter(
'acf/pre_load_value',
function( $meta, $object_id, $field ) {
// Initiate the ACF 'values' store.
$store = acf_get_store( 'values' );
// "prefetched:$object_id" is just to mark that I have previously fetched it.
if ( ! $store->has( "prefetched:$object_id" ) ) {
// Depending on ACF usage this field could be coming from meta or categories.
// For simplicity, lets go basic config only applied to post types.
$meta_type = 'post';
// Get all the object's meta. Could cache this,
// but it will be marked as prefetched, so won't run this
// more than once.
$meta_data = get_metadata( $meta_type, $object_id );
// Time to populate the "values" ACF store.
foreach ( $meta_data as $field_name => $value ) {
// Force singleness of individual values.
$real_value = is_array( $value ) && 1 === count( $value ) ? array_pop( $value ) : $value;
// Ignore hidden keys. Its an ACF thing.
if ( preg_match( '/^_/', $field_name ) ) {
continue;
}
// Where the magic happens.
$store->set( "$object_id:$field_name", $real_value );
}
// Mark it as "done"!
$store->set( "prefetched:$object_id", true );
}
// If value is already fetched then return that value.
$field_name = $field['name'];
if ( $store->has( "$object_id:$field_name" ) ) {
return $store->get( "$object_id:$field_name" );
}
// Fallback to ignore prefetching and let ACF do things the ACF way.
return $meta;
},
10,
3
);
/**
* Other possible things:
*
* 1. Hook `acf/pre_update_value` action to save meta differently (or elsewhere entirely).
* 2. Fetch meta from a different source.
* 3. Hook `acf/load_field` to remove further calls to DB.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment