Function and usage of get_allowed_mime_types() in wordpress


Answers ( 1 )


    The get_allowed_mime_types() function in WordPress is used to retrieve a list of allowed MIME types and file extensions for file uploads. This function is particularly useful for ensuring that users upload only specific types of files, thereby enhancing the security and integrity of your WordPress site. Here's a detailed explanation of its function and usage:


    • Purpose: Retrieves the list of MIME types and file extensions that are allowed for file uploads.
    • Use Case: This function is typically used when you need to check or display the file types that a user is permitted to upload. It's particularly useful in scenarios involving file upload validations and customizations.


    • $user (optional): Can be either an integer (user ID) or a WP_User object.
      • Type: int|WP_User
      • Description: Specifies the user for whom to retrieve the allowed MIME types. If not provided, the function defaults to the current user.
      • Default: null


    • Type: string[] (Array of strings)
    • Description: The function returns an associative array where the keys are file extension regex patterns, and the values are the corresponding MIME types. This array represents the types of files that the specified user is allowed to upload.

    Sample Usage:

    Here's an example of how you might use get_allowed_mime_types() in a WordPress plugin or theme:

    // Get allowed MIME types for the current user
    $allowed_mime_types = get_allowed_mime_types();
    // Optionally, get allowed MIME types for a specific user
    $user_id = 123; // Example user ID
    $specific_user = get_user_by('ID', $user_id);
    $allowed_mime_types_for_user = get_allowed_mime_types($specific_user);
    // Display the allowed file types
    foreach ($allowed_mime_types as $extension => $mime_type) {
        echo "Extension: $extension - MIME Type: $mime_type<br>";

    In this example, the function is first called without any parameters to retrieve the MIME types allowed for the current user. Then, it's called with a specific WP_User object to get the allowed MIME types for that user. The foreach loop is used to iterate over the returned array and display the allowed file extensions and their corresponding MIME types.

Leave an answer