1

We have a custom post type in our plugin and now i must provide the user a meta box where he enters latitude and longitude. I want them to be floats, i have no problems in doing the validation client side, but i don't know how i should handle server side validation in wordpress.

I thought that there was some API for doing this, but this is not the case, so i was just wandering how should i handle things inside my save function.

1 Answer 1

3

Not shure if this isn´t a general php question...

Use the WP_Error Class.

// http://php.net/manual/de/function.is-float.php
// http://php.net/manual/de/function.is-int.php
// inside your save_post/update_post hooks callback function,
// just type cast to float. You could also do a check if it contains non numeric chars
// and then simply return;
$check = ! is_float( $value ) OR ! is_int( $value ) ? new WP_Error( 'wrong value', __(" I've fallen and can't get up", 'YOUR_TEXTDOMAIN_STRING' ), $value ) : $value;

At the end of your function, check if you got an error. To provide a meaningful error message, use jQuery:

if ( is_wp_error( $check ) )
{
    $code = $check->get_error_code();
    $msg = $check->get_error_message();
    // Maybe multiple? You'll have to loop through them
    $msgs = $check->get_error_messages();

    echo "<script type='text/javascript'>
         var error = '<div id=\"message\" class=\"updated below-h2\"><p><strong>{$code}</strong> {$msg}</p></div>';
         // Append the error
         jQuery( '#icon-edit' ).after( error );
    </script>";
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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