Random WordPress Function

Learn about a new WordPress function every day!


Function Signature:

wp_validate_boolean

Function Description:

Filters/validates a variable as a boolean.

Function Examples:

⚠️ Examples below are generated with GPT-3 once every hour. Do not take them too seriously.
Consider them as some extra input in your learning process - reason about them. Will it work? What could fail?
// Example 1: Validating a boolean value from a form submission
$submitted_value = $_POST['is_active']; // Value can be '1' or '0'
$validated_value = wp_validate_boolean( $submitted_value );
if ( $validated_value === false ) {
    // Handle error, maybe set a default value
    $validated_value = false;
}
// Example 2: Using wp_validate_boolean to sanitize a custom field value
$custom_field_value = get_post_meta( $post_id, 'is_featured', true ); // Value can be '1' or '0'
$validated_value = wp_validate_boolean( $custom_field_value );
if ( $validated_value === false ) {
    // Handle error, maybe set a default value
    $validated_value = false;
}
// Example 3: Checking if a boolean value is valid before updating a user meta field
$new_value = $_POST['is_admin']; // Value can be '1' or '0'
if ( wp_validate_boolean( $new_value ) !== false ) {
    update_user_meta( $user_id, 'is_admin', $new_value );
} else {
    // Handle error, maybe display a message to the user
}