Skip to content

Instantly share code, notes, and snippets.

@khromov
Last active January 29, 2019 21:24
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save khromov/2c32d31e5d766a2d6228 to your computer and use it in GitHub Desktop.
Save khromov/2c32d31e5d766a2d6228 to your computer and use it in GitHub Desktop.
Advanced Custom Fields get_field() sanitization
<?php
/**
* Helper function to get sanitized field
* and also normalize values.
*
* @param $field_key
* @param bool $post_id
* @param bool $format_value
* @param string $sanitization_method esc_html / esc_attr or NULL for none
* @return array|bool|string
*/
function get_field_sanitized($field_key, $post_id = false, $format_value = true, $sanitization_method = 'esc_html')
{
$field = get_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_sanitized = array();
foreach($field as $key => $value)
{
$field_sanitized[$key] = ($sanitization_method === NULL) ? $value : $sanitization_method($value);
}
return $field_sanitized;
}
else
return ($sanitization_method === NULL) ? $field : $sanitization_method($field);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment