When updating a post meta where the input will be always an integer, should I use (int) or is there a WordPress function for that (eg. sanitize_text_field)?

For example:

    update_post_meta($post->ID, 'category_id', (int)($_POST['category_id']));

For integers KSES has no special function.

Use (int) or intval() or absint()

See more: Data Validation - Integers

| improve this answer | |
&safe_id = intval( $_POST['category_id'] );
if ( ! $safe_id ) {
  $safe_id = '';

update_post_meta( $post->ID, 'category_id', $safe_id );

The intval() function casts user input as an integer, and defaults to zero if the input was a non-numeric value. We then check to see if the value ended up as zero. If it did, we'll save an empty value to the database. Otherwise, we'll save the properly validated category_id.

| improve this answer | |

Use a conditional statement to check if $_POST['category_id']) is an integer first. The PHP function is is_int()1

if(isset($_POST['category_id']) && is_int($_POST['category_id'])){
    update_post_meta($post->ID, 'category_id', $_POST['category_id']);

You should also trim whitespace on your $_POST data because is_int() will return false if the string has whitespace2.

| improve this answer | |
  • 1
    Your is_int(...) will never work as $_POST always contains strings. – Maxime Dec 29 '19 at 22:28

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.