也许你的问题对你的问题不太清楚。我给出了我理解上述问题的答案。
1. Define a query variable that indicates the requested file
function add_get_file_query_var( $vars ) {
$vars[] = \'get_file\';
return $vars;
}
add_filter( \'query_vars\', \'add_get_file_query_var\' );
2. Update .htaccess to forward requests for restricted files to WordPress
这将捕获对要限制的文件的请求,并使用上面的自定义查询变量将它们发送回WordPress。在重写条件行之前插入以下规则。
RewriteRule ^wp-content/uploads/(.*\\.docx)$ /index.php?get_file=$1
3. Capture the requested file name in custom query variable; and verify access to the file:
function intercept_file_request( $wp ) {
if( !isset( $wp->query_vars[\'get_file\'] ) )
return;
global $wpdb, $current_user;
// Find attachment entry for this file in the database:
$query = $wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE guid=\'%s\'", $_SERVER[\'REQUEST_URI\'] );
$attachment_id = $wpdb->get_var( $query );
// No attachment found. 404 error.
if( !$attachment_id ) {
$wp->query_vars[\'error\'] = \'404\';
return;
}
// Get post from database
$file_post = get_post( $attachment_id );
$file_path = get_attached_file( $attachment_id );
if( !$file_post || !$file_path || !file_exists( $file_path ) ) {
$wp->query_vars[\'error\'] = \'404\';
return;
}
// Logic for validating current user\'s access to this file...
// Option A: check for user capability
if( !current_user_can( \'required_capability\' ) ) {
$wp->query_vars[\'error\'] = \'404\';
return;
}
// Option B: check against current user
if( $current_user->user_login == "authorized_user" ) {
$wp->query_vars[\'error\'] = \'404\';
return;
}
// Everything checks out, user can see this file. Simulate headers and go:
header( \'Content-Type: \' . $file_post->post_mime_type );
header( \'Content-Dispositon: attachment; filename="\'. basename( $file_path ) .\'"\' );
header( \'Content-Length: \' . filesize( $file_path ) );
echo file_get_contents( $file_path );
die(0);
}
add_action( \'wp\', \'intercept_file_request\' );
注意:此解决方案仅适用于单站点安装!这是因为WordPress MU已经通过wp includes/ms文件转发子站点中上传的文件请求。php。WordPress MU也有一个解决方案,但它更复杂一些。