Checking if a UUID is valid in WordPress with wp_is_uuid

The wp_is_uuid function in WordPress is used to check if a given value is a valid UUID (Universally Unique Identifier). This function can be useful for verifying the format of UUIDs before using them in database operations or other code that requires a specific format.

By using wp_is_uuid, developers can ensure that the UUIDs being used in their WordPress projects are correctly formatted, which can help prevent errors and ensure data integrity.

Parameters Accepted by the wp_is_uuid Function

The wp_is_uuid function accepts the following parameters:

  • $uuid (mixed) – Required. Description: UUID to check.
  • $version (int) – Optional. Default value: null. Description: Specify which version of UUID to check against. Default is none, to accept any UUID version. Otherwise, only version allowed is 4.

Value Returned by the wp_is_uuid Function

The function returns a boolean value: true if the string is a valid UUID, or false on failure.

Examples

How to use wp_is_uuid to check if a string is a UUID

Here’s an example of using wp_is_uuid to check if a string is a UUID:

$string = '123e4567-e89b-12d3-a456-426614174000';
if ( wp_is_uuid( $string ) ) {
 echo 'The string is a valid UUID.';
} else {
 echo 'The string is not a valid UUID.';
}

This code snippet checks if the $string is a valid UUID using the wp_is_uuid function and echoes the result.

How to use wp_is_uuid to validate input from a form

Here’s an example of using wp_is_uuid to validate input from a form:

if ( isset( $_POST['uuid'] ) ) {
 $uuid = $_POST['uuid'];
 if ( wp_is_uuid( $uuid ) ) {
 // Process the valid UUID
 } else {
 // Display an error for invalid UUID
 }
}

This code snippet checks if the $_POST['uuid'] is a valid UUID using the wp_is_uuid function and processes it if valid, or displays an error if invalid.

How to use wp_is_uuid in a custom function

Here’s an example of using wp_is_uuid in a custom function:

function process_uuid( $uuid ) {
 if ( wp_is_uuid( $uuid ) ) {
 // Process the valid UUID
 } else {
 // Display an error for invalid UUID
 }
}

This code snippet defines a custom function process_uuid that takes a $uuid parameter and checks if it is a valid UUID using the wp_is_uuid function, then processes it if valid, or displays an error if invalid.

Conclusion

In conclusion, the wp_is_uuid function is a valuable tool for WordPress developers who need to validate UUIDs within their code. By providing a reliable method for checking UUIDs, this function helps ensure the integrity and security of data stored within WordPress databases. Its straightforward usage and clear return values make it a user-friendly addition to the WordPress developer’s toolkit. Whether working with custom post types, user metadata, or plugin data, the wp_is_uuid function offers a convenient solution for UUID validation within the WordPress environment.