The reason your code wasn't working is because you have a typographical error in your code. That code is actually triggering an error. You can enable debug mode to see the error.
But that's not really what's wrong with you code. What's really wrong is that you are using a function that checks a user capability and trying to check a user's role. This works because of how WordPress handles roles and capabilities, but it is not the correct way to check a user's role.
In fact, using a user role in current_user_can()
will likely trigger a _doing_it_wrong()
in the near future. See #38653 Trigger a doing it wrong when checking a role name as a capability. Using current_user_can()
to check a user role has been wrong for a very long time. See this 2006 post, How to check if a WordPress user is an “administrator”, by WordPress lead developer Mark Jaquith
Instead of a role, you should be using a capability with that function.
If you want to check a user's role, then you should do something like the following. There's really no good way to check what role a user has, because they can have multiple roles, and because the user capabilities are not guaranteed to be the same as the roles they are a part of.
add_filter( 'upload_mimes', 'wpse_263936_upload_mimes' );
function wpse_263936_upload_mimes( $mimes ) {
if( ! in_array( 'administrator', wp_get_current_user()->roles ) ) {
$mimes = array(
'jpg|jpeg|jpe' => 'image/jpeg',
'png' => 'image/png',
);
}
return $mimes;
}
If you want to continue using current_user_can()
, you should check a capability such as promote_users
or manage_options
which by default is only applied to the administrator role.
add_filter( 'upload_mimes', 'wpse_263936_upload_mimes' );
function wpse_263936_upload_mimes( $mimes ) {
if( ! current_user_can( 'promote_users' ) ) {
$mimes = array(
'jpg|jpeg|jpe' => 'image/jpeg',
'png' => 'image/png',
);
}
return $mimes;
}
Or you could even define the ALLOW_UNFILTERED_UPLOADS
constant in your wp-config.php
and add the unfiltered_upload
capability to the administrator role and check for that.
functions.php
? The input value forcurrent_user_can()
is wrapped with‘
and’
, you should use'
instead.current_user_can()
will likely trigger a_doing_it_wrong()
in the near future. Instead of a role, you should be using a capability with that function.