Extract all ACF fields as variables

A handy little snippet that allows you to extract all ACF fields attached to a post as named variables.

Advanced Custom fields (ACF) provides its own API to retrieve metadata; get_field() returns the value of a specific field, while get_fields() returns an array of all the values of a post or object. Using the PHP function extract() we can change the array returned by get_fields() as named variables.

Extract all fields from current post

While in the loop get_fields() will return all the fields of the current post.

/**
 * Extracts all ACF fields from current post within the loop
 */

if (function_exists('get_fields')) {
	extract(get_fields());
}

Extract all fields from a specified Object

You can also get all the fields from an object other than the current post, this can be a user, category, custom taxonomy or an option.

/**
 * Extracts all ACF fields from specified object
 */

$object_id = 1; // post with ID = 1
$object_id = "user_2"; // user with ID = 2
$object_id = "category_3"; // category term ID = 3
$object_id = "event_4"; // event (custom taxonomy) term ID = 4
$object_id = "option"; // options page
$object_id = "options"; // options page

if (function_exists('get_fields')) {
	extract(get_fields($object_id));
}

Check if a variable exists before using.

To avoid any errors, it is best to check if a particular variable is set before using it.

/**
 * Check if variable (field) exists
 */

if ($text_field) {
	echo $text_field;
}

if ($repeater_field) {
	foreach ($repeater_field as $row) {
		$sub_field_1 = $row['sub_field_1'];
		$sub_field_2 = $row['sub_field_2'];
	}
}

Avoiding  collisions with existing variables

There may be cases where a variable with the same name already exists before extracting the fields. The extract() function provides a number of flags which  determine how these collisions are treated.

By default any existing variable will be overwritten by the field value with the same name. There are a number of flags that can be passed to keep the value of the existing variable, all the available flags and behaviours can be found here.

If you have previously declared variables I suggest using the EXTR_PREFIX_ALL flag which prefixes all variable names with a chosen prefix, e.g ‘acf_’.

/**
 * Extracts all ACF fields with variable names prefixed with acf_
 */

if (function_exists('get_fields')) {
	extract(get_fields(), EXTR_PREFIX_ALL, 'acf');
}

/**
 * Check if variable (field) exists
 */

if ($acf_text_field) {
	echo $acf_text_field;
}

 

Recent Articles