这可能不是您的全部解决方案,因为您没有发布任何代码,因此我无法将我所知道的内容与任何内容结合起来,但是,下面的代码片段将把一个图像作为附件上传到自定义目录中,该目录是在执行时创建的。我已经对关键行进行了评论。。。
function upload_to_new_dir() {
global $post;
//This gets the main uploads directory
$upload_dir = wp_upload_dir();
//This sets a path to a new directory which we\'ll make, ie. \'/uploads/the-post-slug/\'
$make_new_dir = $upload_dir[\'basedir\'] . $post->post_name;
//Now we check if the directory already exists, if not, we make it
if( !file_exists ( $make_new_dir ) ) :
wp_mkdir_p( $make_new_dir );
endif;
//This gets the image file from an AJAX form for me, you\'ll have to find your own method
$img_file = $_FILES[\'img_file\'];
//Now set WHERE the image is going to be uploaded
$upload_file = $make_new_dir . \'/\' . basename( $img_file[\'name\'] );
//Move the uploaded file to the location specified
move_uploaded_file( $img_file[\'tmp_name\'] , $upload_file );
//Get the name of the image file so we can record it somewhere
$img_name = basename( $upload_file );
//Everything below here is for attaching an image as an $attachement
//And setting it as the post thumbnail
//I don\'t know if this is what you need or if you need another method
$wp_filetype = wp_check_filetype( basename( $img_name ), null );
$attachment = array(
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_title\' => $img_name,
\'post_content\' => \'\',
\'post_status\' => \'inherit\',
\'menu_order\' => $_i + 1000,
);
$img_id = wp_insert_attachment( $attachment, $upload_file );
if( !update_post_meta ( $post->ID, \'_thumbnail_id\', $img_id ) ) {
add_post_meta( $post->ID, \'_thumbnail_id\', $img_id, true );
};
set_post_thumbnail( $post->ID, $img_id );
}
//YOU NEED TO DETERMINE WHAT ACTION TO USE TO EXECUTE THIS
我的建议是不要干扰媒体库的默认操作,而是构建自己的函数,从管理端javascript使用AJAX执行。
如果你这样做,你想要的行动是
add_action(\'wp_ajax_nameofajaxaction\', \'upload_to_new_dir\');
您还需要创建一个nonce,并在上述函数的开头使用以下各项检查nonce:
check_ajax_referer();
一些轻松的阅读:
https://developer.wordpress.org/reference/functions/check_ajax_referer/https://codex.wordpress.org/AJAX_in_Plugins