How to Force Users to be Logged In to Download Purchased Files in WordPress

Home » Snippets » How to Force Users to be Logged In to Download Purchased Files in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you running an online store on WordPress and want to protect your purchased files from unauthorized access? One effective way to achieve this is by requiring users to be logged in before they can download their purchased files. In this article, we will explore the step-by-step process of forcing users to be logged in in order to access and download purchased files on your WordPress website. By implementing this security measure, you can ensure that only the intended users have access to your valuable digital products. Let’s dive in and learn how to add this extra layer of protection to your online store.

					function wpturbo_force_logged_in_to_download( $url ) {
    if ( !is_user_logged_in() ) {
        $url = wp_login_url( $url );
    }
    return $url;
}
add_filter( 'edd_download_file_url', 'wpturbo_force_logged_in_to_download' );
				

The code snippet provided here aims to solve the problem of restricting the download of purchased files on a WordPress website to logged-in users only.

To achieve this, we define a new function called wpturbo_force_logged_in_to_download(). This function takes a parameter, $url, which represents the download URL of the file.

Within the function, we check whether the current user is logged in or not using the is_user_logged_in() function. If the user is not logged in, we modify the $url variable to redirect them to the WordPress login page by using the wp_login_url() function, passing in the original $url as the redirect URL.

The modified $url is then returned from the function.

Finally, we hook the wpturbo_force_logged_in_to_download() function into the edd_download_file_url filter. The edd_download_file_url filter provides us with the ability to modify the download URL before it is rendered, allowing us to enforce the logged-in requirement for file downloads.

By adding our function to this filter, every time a download URL is requested, our function will be called and the modification will take place, ensuring that only logged-in users can access the download.

Overall, this code snippet provides a simple and effective way to restrict download access to logged-in users on a WordPress website using the Easy Digital Downloads plugin.

Register an account to save your snippets or go Pro to get more features.