Private/ Pay Wall Media in WordPress

One of the biggest issues when creating a private WordPress backed web application or social network is restricting access to media files. Here is how to solve it.

To restrict access to media files in WordPress so that only logged-in users can view them, you can modify the .htaccess file in the root of your WordPress directory. Add the following code to the .htaccess file:

RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^wp-content/uploads/(.*)$ d3s-file.php?file=$1 [QSA,L]

Then, create a file named d3s-file.php in the root of your WordPress directory and add the following code to it:

if (!is_user_logged_in()) {
    $upload_dir = wp_upload_dir();
    echo $upload_dir['baseurl'] . '/' . $_GET['file'];
    wp_redirect(wp_login_url($upload_dir['baseurl'] . '/' . $_GET['file']));
    exit();
}

This code checks if the user is logged in. If not, it redirects them to the login page with a parameter that redirects them back to the file after logging in

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *