Last active
January 29, 2019 21:24
-
-
Save khromov/2c32d31e5d766a2d6228 to your computer and use it in GitHub Desktop.
Advanced Custom Fields get_field() sanitization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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