Discover in this tutorial how to make sure that a given user role can only upload images with a specific aspect ratio thanks to a simple code snippet.
If you manage a website where users/subscribers can upload their profile images you may have encountered the problem that each image has a different aspect ratio (square, rectangular…) and when the profiles are displayed they look too heterogeneous.
One way to make the design more homogeneous is to force users to upload images with the same aspect ratio (for example, that they are all square).
You can achieve this with some code that checks the image attributes when the user is uploading it.
Let’s see an example of how to achieve this.
Snippet to limit image uploads to a certain aspect ratio
Add the following code at the end of functions.php or in your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
In this code you use the wp_handle_upload_prefilter
filter together with the current_user_can
function so that, if the user is not an administrator, they can only upload square images.
That is, if the user tries to upload an image that does not have a 1:1 aspect ratio (square) they will receive an error.
On the other hand, users with administrator role will still be able to upload any type of image to WordPress.
This is just an example, you can customize it to affect different user roles and/or use other aspect ratios.
Conclusion
Now you know how to make it so that a certain user role can only upload images with the aspect ratio you need to maintain visual consistency (for example).
Any questions? Let me know in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉