Home Forums Feature Requests Improve ACF performance – implement a simple caching (an example provided) Reply To: Improve ACF performance – implement a simple caching (an example provided)

  • Hi guys

    This is a great topic.

    Currently, ACF will cache any value loaded from the DB, but after loading, the $value is sent to another function that formats it based on the field type.

    When dealing with the repeater / gallery field, this results in a lot of extra logic / DB calls.

    I have caching setup for the loading of values, but not for the formatting of values.
    I wonder if we adding caching to the format function, this will fix the issue.

    The following assumes you are using ACF PRO (or ACF v5 in the future):

    Open the file api/api-value.php and finc the acf_get_value function. Below this function is the acf_format_value function. Note that the format function contains no caching, but the load function does.

    Try changing the format function to this:

    *  acf_format_value
    *  This function will format the value for front end use
    *  @type	function
    *  @date	3/07/2014
    *  @since	5.0.0
    *  @param	$value (mixed)
    *  @param	$post_id (mixed)
    *  @param	$field (array)
    *  @return	$value
    function acf_format_value( $value, $post_id, $field ) {
    	// try cache
    	$found = false;
    	$cache = wp_cache_get( "format_value/post_id={$post_id}/name={$field['name']}", 'acf', false, $found );
    	if( $found ) return $cache;
    	// apply filters
    	$value = apply_filters( "acf/format_value", $value, $post_id, $field );
    	$value = apply_filters( "acf/format_value/type={$field['type']}", $value, $post_id, $field );
    	$value = apply_filters( "acf/format_value/name={$field['name']}", $value, $post_id, $field );
    	$value = apply_filters( "acf/format_value/key={$field['key']}", $value, $post_id, $field );
    	// update cache
    	wp_cache_set( "format_value/post_id={$post_id}/name={$field['name']}", $value, 'acf' );
    	// return
    	return $value;

    Does it work? I’ll do some testing too, but would be great to hear back from you @wube