当我的用户上传文件时,我需要使用特定的 user_meta 值重命名该文件。所以,使用wp_handle_upload
我为$upload_overrides
设置了一个回调函数,如下所示:
$upload_overrides = array( 'test_form' => false, 'unique_filename_callback' => 'change_document_name' );
我的回调函数是
function change_document_name($dir, $name, $ext){
global $current_user;
$doc_type = get_user_meta($current_user->ID, 'document_type', true);
return $doc_type . '_mydoc' . $ext;
}
现在您可以看到,我们正在讨论用户文档,因此我需要根据他们上传的文档类型重命名它们。例如,如果他们上传了“护照”并选择了文档类型(当然),我应该获取user_meta
'document_type',将其用作前缀并将其放入上传文件名的前面,输出类似
当然我的功能不起作用,我不明白为什么它不采用全局$ current_user或至少是否有其他方法来实现这一点。
非常感谢。
修改
为了更好地解释它,我的错,函数change_document_name()
确实重命名了这个文件:
这意味着该函数被正确调用并运行,除了忽略$doc_type
变量的第一部分。出于这个原因,我认为 $ current_user 它不起作用。我上传文件的完整代码如下:
if(!empty($_FILES['docfile'])):
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
$upload_overrides = array( 'test_form' => false, 'unique_filename_callback' => 'change_document_name' );
add_filter('upload_dir', 'my_user_folder'); //A documents custom folder
$uploaded_file = wp_handle_upload($_FILES['docfile'], $upload_overrides);
remove_filter( 'upload_dir', 'my_user_folder' );
$doc_file_loc = $uploaded_file['file'];
$doc_file_title = $_FILES['docfile']['name'];
$doc_file_arr = wp_check_filetype(basename($_FILES['docfile']['name']));
$doc_file_type = $doc_file_arr['type'];
$doc_file_att = array(
'post_mime_type' => $doc_file_type,
'post_title' => addslashes($doc_file_title),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => 0,
'post_author' => $uid
);
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$doc_file_id = wp_insert_attachment( $doc_file_att, $doc_file_loc, 0 );
$doc_file_url = wp_get_attachment_url( $doc_file_id );
update_user_meta($uid,'document_file', $doc_file_url);
endif;
根据此处的代码x https://developer.wordpress.org/reference/functions/wp_unique_filename/
使用钩子'unique_filename_callback'
答案 0 :(得分:1)
我不确定为什么全局不会返回用户。它应该是。但请尝试get_current_user_id()
,看看它是否有效:
function change_document_name( $dir, $name, $ext ){
if ( ! is_user_logged_in() ) {
error_log( "User not logged in." );
return;
}
$user_id = get_current_user_id();
// Uncomment to see if there is any value
// var_dump( $user_id );
$doc_type = get_user_meta( $user_id, 'document_type', true );
// Uncomment to see if there is any value
// var_dump( $doc_type );
if ( ! $doc_type ) {
error_log( "There is no doc type set for the current user with id $user_id" );
return;
}
return $doc_type . '_mydoc' . $ext;
}
我在那里添加了一些var_dump,您可以使用它们来查看返回的值,或者如果您设置了xdebug,则可以调试。但这应该会给你你需要的东西。如果您不想记录这些错误,也可以删除错误日志记录。它们在那里,因此您可以检查站点日志并查看其中的内容。