Sanitize Array inside save_post

3.4k views Asked by At

Let's say I have array like this :

   Array (

   [2066] => Array (
        [images_id] => 2066
        [title] => title one)

   [2063] => Array (
        [images_id] => 2063
        [title] => title two )

   [2022] => Array (
        [images_id] => 2022
        [title] => title three )

   ) 

or in database format like this:

    a:3:{i:2066;a:2:{s:8:"image_id";s:4:"2066";s:5:"title";s:9:"Title One";}i:2063;a:2:{s:8:"image_id";s:4:"2063";s:5:"title";s:9:"Title Two";}i:2022;a:2:{s:8:"image_id";s:4:"2022";s:5:"title";s:11:"Title Three";}}

How to sanitize with esc_attr or sanitize_text_field for images_id and title ?

Any help really appreciated :)

1

There are 1 answers

1
Reza Mamun On BEST ANSWER

You can sanitize the images_id and the title fields of the array with Wordpress's esc_attr() and sanitize_text_field() functions using the PHP's array_walk() like below:

<?php
$arr = array(
   2066 => array (
        'images_id' => 2066,
        'title' => 'title one'
   ),
   2063 => array (
        'images_id' => 2063,
        'title' => 'title two'
   ),
   2022 => array (
        'images_id' => 2022,
        'title' => 'title three'
   )
);

//Sanitizing here:
array_walk($arr, function(&$value, &$key) {
    $value['images_id'] = esc_attr($value['images_id']);
    $value['title'] = esc_attr($value['title']);

    //--AND/OR--
    $value['images_id'] = sanitize_text_field($value['images_id']);
    $value['title'] = sanitize_text_field($value['title']);
});

//Now check the new array:
echo '<pre>'; print_r($arr); echo '</pre>';

?>