0

I tried this code to create some meta boxes is all working fine, the problem I am facing is how to sanitize the text fields and update post meta

    function Print_price_fileds($cnt, $p = null) {
    if ($p === null){
    $a = $b = $c = '';
    }else{
    $a = $p['n'];
    $b = $p['d'];
    $c = $p['p'];
    }
    return  <<<HTML
    <li>
    <label>Nr :</label>
    <input type="text" name="price_data[$cnt][n]" size="10" value="$a"/>

    <label>Description :</label>
    <input type="text" name="price_data[$cnt][d]" size="50" value="$b"/>

    <label>Price :</label>
    <input type="text" name="price_data[$cnt][p]" size="20" value="$c"/>
    <span class="remove">Remove</span>
    </li>
    HTML
    ;
    }


    //add custom field - price
    add_action("add_meta_boxes", "object_init");

    function object_init(){
      add_meta_box("price_meta_id", "Price fields :","price_meta", "post", 
    "normal", "low");

    }

    function price_meta(){
     global $post;

    $data = get_post_meta($post->ID,"price_data",true);
     echo '<div>';
     echo '<ul id="price_items">';
     $c = 0;
     if (count($data) > 0){
        foreach((array)$data as $p ){
            if (isset($p['p']) || isset($p['d'])|| isset($p['n'])){
                echo Print_price_fileds($c,$p);
                $c = $c +1;
            }
        }

    }
    echo '</ul>';

    ?>
        <span id="here"></span>
        <span class="add"><?php echo __('Add Price Data'); ?></span>
        <script>
            var $ =jQuery.noConflict();
                $(document).ready(function() {
                var count = <?php echo $c - 1; ?>; // substract 1 from $c
                $(".add").click(function() {
                    count = count + 1;
                    //$('#price_items').append('<li><label>Nr :</label><input type="text" name="price_data[' + count + '][n]" size="10" value=""/><label>Description :</label><input type="text" name="price_data[' + count + '][d]" size="50" value=""/><label>Price :</label><input type="text" name="price_data[' + count + '][p]" size="20" value=""/><span class="remove">Remove</span></li>');
                   $('#price_items').append('<? echo implode('',explode("\n",Print_price_fileds('count'))); ?>'.replace(/count/g, count));
                    return false;
                });
                $(".remove").live('click', function() {
                    $(this).parent().remove();
                });
            });
        </script>
        <style>#price_items {list-style: none;}</style>
    <?php
    echo '</div>';
}


    //Save product price
    add_action('save_post', 'save_detailss');

    function save_detailss($post_id){ 
    global $post;


    // to prevent metadata or custom fields from disappearing... 
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
    return $post_id; 
    // OK, we're authenticated: we need to find and save the data
    if (isset($_POST['price_data'])){
        $data = $_POST['price_data'];
        update_post_meta($post_id,'price_data',$data);
    }else{
        delete_post_meta($post_id,'price_data');
    }
} 
1

The best way to sanitize text fields within WordPress is to use sanitize_text_field() function:

$data = sanitize_text_field( $_POST['key'] );

Additionally, if you register the meta field properly width register_meta() function, you can define the sanitize callback and the expected data type as well. For example:

add_action( 'init', 'cyb_register_meta_fields' );
function cyb_register_meta_fields() {
  $args = array(
    'sanitize_callback' => 'sanitize_text_field'
  );
  register_meta( 'post', 'key', $args );
}

By using register_meta() you don't need to sanitize the meta field every time you upadate or create it, just use upadate_post_meta()/add_post_meta() and the sanitize callback will be used automatically. So, if your meta field is an array, it could be something like this:

add_action( 'init', 'cyb_register_meta_fields' );
function cyb_register_meta_fields() {

  $args = array(
    'sanitize_callback' => 'sanitize_price_field'
  );

  register_meta( 'post', 'price_data', $args );

}

function sanitize_price_field( $meta_value ) {

  foreach ( (array) $meta_value as $k => $v ) {
    if ( is_array( $v ) ) {
      $meta_value[$k] =  sanitize_price_field( $v );
    } else {
      $meta_value[$k] = sanitize_text_field( $v );
    }
  }

  return $meta_value;

}
  • it didn't work, but thank you any way !! – gp el Jun 21 '17 at 14:56
  • Can you explain what "didn't work" exactly means? Can you update the question with the exact code you have tried? I use a similar approach everytime I create a custom field and it works perfectly. – cybmeta Jun 21 '17 at 15:07
  • Well, the array_walk_recursive() callback needs to get the data passed by reference in order to change the original array, I think that was the problem with the answer not working. Code updated. – cybmeta Jun 21 '17 at 15:20
2

Wordpress use add_magic_quotes() to escape incoming data from $_POST, $_GET and $_COOKIEand $_SERVERin load.php on line 647. You can use structur of this function to build Your own function which can sanitize every element in array:

function add_magic_quotes( $array ) {
    foreach ( (array) $array as $k => $v ) {
        if ( is_array( $v ) ) {
            $array[$k] = add_magic_quotes( $v );
        } else {
            $array[$k] = addslashes( $v );
    }
}
return $array;

}

in place of addslashes You can use your needed function. Example:

function sanitize_price_array( $array ) {
   foreach ( (array) $array as $k => $v ) {
      if ( is_array( $v ) ) {
          $array[$k] =  sanitize_price_array( $v );
      } else {
          $array[$k] = sanitize_text_field( $v );
      }
   }

  return $array;                                                       
}

$data = sanitize_price_array( $_POST['price_data']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.