• Skip to primary navigation
  • Skip to main content
OsomCode

OsomCode

Awesome code tutorials for WordPress and Genesis

  • Subscribe
  • My account
    • Edit profile
    • Favorites
    • Update credit card
  • Login

Limiting image uploads to a certain aspect ratio in WordPress

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 965 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.

error message upload rectangular image WordPress
Error message that will be displayed if they try to upload an image that is not square

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. 😉

PHP WordPress

To leave read and make questions about this code, you can login or register.

  • About OsomCode
  • FAQ
  • Contact

Legal Notice · Privacy Policy · Cookie Policy · Terms and conditions
Copyright © 2023

Lost your password?