我正在建立一个会员网站,其中会有需要公开提供的文件(网站资产)和仅需要为会员私密的文件。
我在uploads文件夹中创建了一个名为'private'的目录,并将根.htaccess设置为以下内容:
RewriteCond %{REQUEST_URI} ^.*wp-content/uploads/private/.*
RewriteRule ^wp-content/uploads/(private/.*)$ wp-private.php?file=$1 [QSA,L]
然后我按照此处的说明访问私人目录中的文件:https://gist.github.com/hakre/1552239
我还在functions.php中添加了一些函数,以便将文件设置为私有或不私有:
function attachment_fields_to_edit_isprivate( $form_fields, $post ) {
$isprivate = get_post_meta($post->ID, '_isprivate', true);
$checked = ($isprivate) ? 'checked' : '';
$form_fields['isprivate'] = array(
'label' => 'Private',
'input' => 'html',
'html' => "<input type='checkbox' {$checked} name='attachments[{$post->ID}][isprivate]' id='attachments[{$post->ID}][isprivate]' />",
'value' => $isprivate
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'attachment_fields_to_edit_isprivate', null, 2 );
function attachment_fields_to_save_isprivate($post, $attachment) {
$isprivate = ($attachment['isprivate'] == 'on') ? '1' : '0';
update_post_meta($post['ID'], '_isprivate', $isprivate);
return $post;
}
add_filter( 'attachment_fields_to_save', 'attachment_fields_to_save_isprivate', null, 2 );
add_action( 'edit_attachment', 'wpse_70093_modify_uploaded_file_title' );
function wpse_70093_modify_uploaded_file_title( $attachment_ID )
{
$isprivate = get_post_meta($attachment_ID, '_isprivate', true);
$uploads = wp_upload_dir();
$upload_path = $uploads['basedir'];
$meta = wp_get_attachment_metadata($attachment_ID);
$path = pathinfo($upload_path.'/'.$meta['file']);
if($isprivate == 1){
rename($path['dirname'].'/'.basename($meta['file']),$uploads['basedir'].'/private/'.basename($meta['file']));
foreach($meta['sizes'] as $k => $v){
rename($path['dirname'].'/'.$v['file'],$uploads['basedir'].'/private/'.$v['file']);
}
$meta['file'] = 'private/'.basename($meta['file'] );
update_attached_file( $attachment_ID, 'private/'.basename($meta['file'] ));
wp_update_attachment_metadata( $attachment_ID, $meta );
}else{
rename($path['dirname'].'/'.basename($meta['file']),$uploads['basedir'].$uploads['subdir'].'/'.basename($meta['file']));
foreach($meta['sizes'] as $k => $v){
rename($path['dirname'].'/'.$v['file'],$uploads['basedir'].$uploads['subdir'].'/'.$v['file']);
}
$meta['file'] = ltrim($uploads['subdir'], '/').'/'.basename($meta['file'] );
update_attached_file( $attachment_ID, ltrim($uploads['subdir'], '/').'/'.basename($meta['file'] ));
wp_update_attachment_metadata( $attachment_ID, $meta );
}
}
当文件设置为私有时,我的函数会将文件从uploads目录移动到私有目录,当文件没有设置为private时,它将反转它。
我的问题是,当我将文件设置为私有时,由于我设置的htaccess,wp-admin无法读取文件。
有没有我可以设置htaccess所以我可以从wp-admin查看私人文件?
或者,如果有人在不使用插件的情况下拥有更好或更优雅的解决方案,我会非常感激,因为我觉得我在这里所做的事情太过分了。
更新: 这是媒体管理器中发生的事情的屏幕截图...