Well, lots of WPFTS Pro users asked: how we can prevent open/download attachment (PDF, DOCX) files from non-authorized users? They want files to be found by their content and then shown in search results. But when the non-authorized user trying to open this file, he should be redirected to the special page where he can log in or buy access, etc.
The solution is pretty simple and only contains a dozen lines of PHP code.
The idea is to show "attachment page" links instead of direct links to files in search results (you can get this using the respective checkbox in WPFTS Settings). And then replace this attachment page with the simple script which is checking user rights and make a proper action: whether redirection to the "login page" or outputs the file data without disclosing the actual file path.
First, we need to find the single-attachment.php
file in the root of your current theme (or better, child theme).
In case the file does not exist, we need to create an empty one.
Next step, we should put the code in this file like this:
<?php
global $post; // Current post (attachment)
// Check user rights
// Note: this piece can be different depending on the user access management plugin which you're using
$is_allowed = false;
if (is_user_logged_in()) {
// User is logged in
$user = wp_get_current_user();
// Check the user rights
if (in_array('customer', $user->roles) || in_array('administrator', $user->roles)) {
// User is a customer or admin
$is_allowed = true;
}
}
if ($is_allowed) {
// Output file data
$fn = get_attached_file($post->ID);
if (is_file($fn) && file_exists($fn)) {
$mime = mime_content_type($fn);
header('Content-Type: '.$mime);
//header('Content-Disposition: attachment; filename="'.basename($fn).'"'); // Download
header('Content-Disposition: inline; filename="'.basename($fn).'"'); // Open inline
readfile($fn); // Passthrou the file data
} else {
// File error
header('HTTP/1.0 404 Not Found');
header('Content-Type: text/plain');
echo 'This file is not available. Please check the link.';
}
} else {
// Show "not enough rights" message or redirect to the proper page
// Case 1: Show the message
//header('Content-Type: text/plain');
//echo 'Not enough rights to download this file. Please log in and ensure that you have proper license.';
// Case 2: Redirect to the "payment page" or "login page", whatever you need
header('Location: /wp-login.php&redirect_to='.urlencode($_SERVER['REQUEST_URI']));
}
exit();
This is a sample code, which means that you need to change some pieces for your exact website.
Hope it's understood. If you have questions - ask below. Thanks!