Halloween Sale 15% off Ends in See the plans
PHP

Allow Font, eBook and Data File Uploads for Administrators

Lets administrators upload web fonts (WOFF, WOFF2, TTF, OTF), EPUB eBooks, JSON and GPX files to the Media Library, which WordPress blocks by default.

Don’t have WPIDE yet? Install it on your site

Code

// Extension => MIME type allowed for administrators.
$wpide_extra_mimes = array(
    'woff'  => 'font/woff',
    'woff2' => 'font/woff2',
    'ttf'   => 'font/ttf',
    'otf'   => 'font/otf',
    'epub'  => 'application/epub+zip',
    'json'  => 'application/json',
    'gpx'   => 'application/gpx+xml',
);

add_filter( 'upload_mimes', function ( $mimes, $user = null ) use ( $wpide_extra_mimes ) {
    $user_id = $user instanceof WP_User ? $user->ID : ( $user ? (int) $user : get_current_user_id() );

    if ( user_can( $user_id, 'manage_options' ) ) {
        $mimes = array_merge( $mimes, $wpide_extra_mimes );
    }

    return $mimes;
}, 10, 2 );

// File type detection often reports these formats differently; trust the extension for administrators.
add_filter( 'wp_check_filetype_and_ext', function ( $data, $file, $filename ) use ( $wpide_extra_mimes ) {
    if ( ! empty( $data['ext'] ) || ! current_user_can( 'manage_options' ) ) {
        return $data;
    }

    $ext = strtolower( pathinfo( (string) $filename, PATHINFO_EXTENSION ) );

    if ( isset( $wpide_extra_mimes[ $ext ] ) ) {
        return array( 'ext' => $ext, 'type' => $wpide_extra_mimes[ $ext ], 'proper_filename' => false );
    }

    return $data;
}, 10, 3 );

Notes

Other roles keep the default list. Add or remove extensions in $wpide_extra_mimes.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.