March 7, 2024

Restrict WordPress Media Access with a Code Snippet

Play Video

Learn how to restrict WordPress media access based on user role to keep an organized workflow. This tutorial will guide you through the process of restricting WordPress media access using a code snippet, leveraging the FluentSnippets plugin as our tool of choice.


Prerequisites

Please make sure you have the following installed and activated:


Why You Would Want to Restrict WordPress Media Access

Restricting media access in WordPress can be crucial for a variety of reasons, catering to both operational efficiency and enhanced security measures within your website. Here are key reasons why implementing such restrictions can be beneficial for your site management and user experience:

  • Privacy and Security
    In a multi-user environment, ensuring that users can only access their own uploads is vital for maintaining privacy and security. It prevents unauthorized access to sensitive or private media files, which could potentially be misused if accessible by all users.
  • Clean and Organized Dashboard
    By limiting media access to user-specific files, each user experiences a cleaner and more organized media library. This reduces clutter and makes it easier for users to find and manage their own uploads without sifting through irrelevant files.
  • Enhanced Performance
    For websites with a large number of users and uploads, restricting access can indirectly improve the performance of the media library interface. Users will encounter faster loading times and smoother navigation since the system only loads a subset of the total media files.
  • User Role Management
    This practice reinforces the principles of user role management by adhering to the least privilege strategy—users have only the permissions necessary for their role. It streamlines workflows and minimizes the risk of accidental or intentional alterations to other users’ media files.
  • Professionalism and Accountability
    When users know they are accountable only for their media content, it fosters a sense of responsibility and professionalism. This is particularly important in environments where content quality and copyright compliance are paramount.
  • No Extra Plugin Dependency
    While numerous plugins offer this functionality, relying on additional plugins can bloat your WordPress installation, potentially slowing down your site and posing security risks. Implementing a code snippet solution provides a lightweight and direct approach, reducing the need for extra plugins and the complications that come with them.

Instructions to Restrict WordPress Media Access with a Snippet

  1. Install and activate the FluentSnippets plugin and navigate to FluentSnippets > New Snippet.
    Install and activate the FluentSnippets plugin and navigate to FluentSnippets > New Snippet
    Note: You also can use any other code snippet plugin.
  2. Enter a descriptive title for your snippet, such as “Restrict Media Library Access” and paste the following PHP code snippet in the code area:
    <?php
    /**
     * Filter the media library query to show only the current user's uploads, except for administrators or the original authors.
     *
     * @param WP_Query $query The WP_Query instance.
     */
    function restrict_media_library( $query ) {
        // Get the current user's ID
        $current_user_id = get_current_user_id();
    
        // Get the current user's roles
        $current_user_roles = wp_get_current_user()->roles;
    
        // Check if the current user is an administrator or the original author
        if ( in_array( 'administrator', $current_user_roles ) || $query->get( 'author' ) == $current_user_id ) {
            return; // Allow access to administrators and the original authors
        }
    
        // Retrieve the original author's ID from the queried post
        $original_author_id = (int) $query->get( 'author' );
    
        // Check if the current user is the original author
        if ( $original_author_id === $current_user_id ) {
            return; // Allow access to the original author
        }
    
        // Set the author query parameter to the current user's ID
        $query->set( 'author', $current_user_id );
    }
    
    add_action( 'pre_get_posts', 'restrict_media_library' );

    Source: Learnbricksbuilder.com

  3. Select ‘Run snippet everywhere’ to ensure it works both on the frontend and the dashboard. Save/update your snippet to activate it.
    Select 'Run snippet everywhere' to ensure it works both on the frontend and the dashboard
  4. Test the functionality by logging in as different users to ensure that authors and editors can only see their own uploads, while administrators can see all files.

Official Documentation


Conclusion of Restricting WordPress Media Access

By following these steps, you can easily restrict WordPress media access without relying on additional plugins, ensuring a cleaner and more streamlined WordPress backend. This approach not only enhances site security but also simplifies the user experience for your team. Remember, while FluentSnippets simplifies the process, the core principles can be applied directly within your theme’s functions.php file, offering flexibility and control over your WordPress site’s functionality.

Required Resources

Credit to WPTuts
WPTuts is a popular YouTube channel dedicated to providing high-quality, easy-to-follow tutorials for WordPress enthusiasts, web designers, and developers. The channel features a wide range of topics, from beginner guides on setting up your first WordPress site to advanced tutorials on customizing themes and plugins, ensuring that there's something for everyone
Visit
Restrict WordPress Media Access with a Code Snippet
Welcome back!
Enter your Helwp credentials to sign in.

No Account yet? Sign Up

My Account
Menu
Give Feedback
Describe your feedback *
Rate Helwp
Share
Facebook
Twitter
LinkedIn
Reddit
Email
WhatsApp
Telegram
Pocket
Report
Problem *
Describe the problem
Want us to reply?
Your E-Mail
Affiliate Disclosure

At Helwp, we’re committed to transparency and honesty. Therefore, we want to inform you that some of the links on our website are affiliate links. This means that, at no additional cost to you, we may earn a small commission if you click through and make a purchase.

We only promote products or services that we genuinely believe in. These affiliate commissions help us to maintain the website and continue to provide you with free, high-quality WordPress content.

If you are interested in how you can support us even further, check out our support page.