Search code examples
wordpresspost-meta

WP How can i save a comma format number in a meta field


I have added a custom field to the post Editor to save a temperature as number value. If i put for example "15,2" or "15.2" in this field and save the post, its get saved as "152".

How can i fix it?

Form Field:

<label for="temp_min">Temp Min.:</label><br />
    <input class="widefat" type="text"  name="temp_min" id="temp_min" value="<?php echo esc_attr( get_post_meta( $object->ID, '_temp_min', true ) ); ?>" size="30" /> 

save class:

      /* Get the posted data and sanitize it for use as an HTML class. */
  $new_meta_value = ( isset( $_POST[$fields[$i]] ) ? sanitize_html_class( $_POST[$fields[$i]] ) : '' );

  /* Get the meta key. */
   $meta_key = $meta_keys[$i];

  /* Get the meta value of the custom field key. */
  $meta_value = get_post_meta( $post_id, $meta_key, true );

  /* If a new meta value was added and there was no previous value, add it. */
  if ( $new_meta_value && '' == $meta_value )
    add_post_meta( $post_id, $meta_key, $new_meta_value, true );

  /* If the new meta value does not match the old value, update it. */
  elseif ( $new_meta_value && $new_meta_value != $meta_value )
    update_post_meta( $post_id, $meta_key, $new_meta_value );

  /* If there is no new meta value but an old value exists, delete it. */
  elseif ( '' == $new_meta_value && $meta_value )
    delete_post_meta( $post_id, $meta_key, $meta_value );
  }  

Solution

  • sanitize_html_class remove . or , so 19,5 or 19.5 will result to 195.

    Strips the string down to A-Z,a-z,0-9,_,-.

    WP codex : https://codex.wordpress.org/Function_Reference/sanitize_html_class

    Just use sanitize_text_field or (float) $_POST[$fields[$i]]:

    /* Get the posted data and sanitize it for use as an HTML class. */
    $new_meta_value = ( isset( $_POST[$fields[$i]] ) ? sanitize_text_field( $_POST[$fields[$i]] ) : '' );