WordPress在日常主题插件开发中,保存内容时需要使用 sanitize_text_field
函数来保证数据的安全。
Clean everything, check everything, escape everything, and never trust the users to always have input sane data. After all, users come from all walks of life.
- https://developer.wordpress.org/plugins/security/securing-input/
- https://developer.wordpress.org/plugins/security/securing-output/
但是当我们需要保存一个数组时,比如多个input框,使用同一个name时,就需要用到。这里我们写一个具体的函数
function sanitize_text_or_array_field($array_or_string)
{
if (is_string($array_or_string)) {
$array_or_string = sanitize_text_field($array_or_string);
} elseif (is_array($array_or_string)) {
foreach ($array_or_string as $key => &$value) {
if (is_array($value)) {
$value = $this->sanitize_text_or_array_field($value);
} else {
$value = sanitize_text_field($value);
}
}
}
return $array_or_string;
}