By
05/13/2016   Comments Off on Escape Fields in ACF

View all snippets

Sometimes you want to prevent users, either on the backend or frontend from inputting JS, HTML and other things that may cause problems into you custom fields. This function prevents that:

 
function get_sub_field_escaped($field_key, $post_id = false, $format_value = true, $escape_method = 'esc_html')
 {
 $field = get_sub_field($field_key, $post_id, $format_value);
 
 /* Check for null and falsy values and always return space */
 if($field === NULL || $field === FALSE)
 $field = '';
 
 /* Handle arrays */
 if(is_array($field))
 {
 $field_escaped = array();
 foreach($field as $key => $value)
 {
 $field_escaped[$key] = ($escape_method === NULL) ? $value : $escape_method($value);
 }
 return $field_escaped;
 }
 else
 return ($escape_method === NULL) ? $field : $escape_method($field);
 }

Then use this for fields you wanted escaped like so:

the_field_escaped('description');
get_field_escaped('description');
get_sub_field_escaped('description');

See the reference here