wordpress收费下载资源主题
wordpress付费下载资源插件

wordpress前台某处上传图片到媒体库单独放进一个文件夹

最近模板兔给某个客户二次开发时,需要对前台工单里上传的图片单独放入一个ticket文件夹且也走媒体库逻辑。比如默认上传到媒体库是wp-content/upload/2026/06/目录,我这个前台上传工单图片到wp-content/upload/ticket/2026/06/目录。

前台原始上传代码:

if ( ! function_exists( 'wp_handle_upload' ) ) { require_once( ABSPATH . 'wp-admin/includes/file.php' ); } $upload = wp_handle_upload($_FILES['imageFile'], array('test_form' => false)); if ($upload && !isset($upload['error'])) { $attachment = array( 'guid' => $upload['url'], 'post_mime_type' => $upload['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', basename($upload['file'])), 'post_content' => '', 'post_status' => 'inherit' ); $attachment_id = wp_insert_attachment($attachment, $upload['file']); if (!is_wp_error($attachment_id)) { require_once( ABSPATH . 'wp-admin/includes/image.php' ); // 生成元数据并更新附件 $attachment_data = wp_generate_attachment_metadata($attachment_id, $upload['file']); wp_update_attachment_metadata($attachment_id, $attachment_data); $image = wp_get_attachment_url($attachment_id); $error = 0; } }

修改后的代码:

if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}

add_filter('upload_dir', function($upload) {
$custom_subdir = '/ticket' . $upload['subdir'];
$upload['path'] = $upload['basedir'] . $custom_subdir;
$upload['url'] = $upload['baseurl'] . $custom_subdir;
$upload['subdir'] = $custom_subdir;
return $upload;
}, 99);

$upload = wp_handle_upload($_FILES['file'], array('test_form' => false));

// 上传完立即移除过滤器,不影响其他代码
remove_filter('upload_dir', 99);

if ($upload && !isset($upload['error'])) {
$attachment = array(
'guid' => $upload['url'],
'post_mime_type' => $upload['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($upload['file'])),
'post_content' => '',
'post_status' => 'inherit'
);

$attachment_id = wp_insert_attachment($attachment, $upload['file']);

if (!is_wp_error($attachment_id)) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );

// 生成元数据并更新附件
$attachment_data = wp_generate_attachment_metadata($attachment_id, $upload['file']);
wp_update_attachment_metadata($attachment_id, $attachment_data);

$image = wp_get_attachment_url($attachment_id);

$error = 0;
}
}

0 个评论

定制开发
本站承接WordPress等系统建站仿站、二次开发、主题插件定制等开发服务
在线咨询
  • 请先加Q,临时会话收不到
    QQ:1-247-246-247

  • QQ一群:104228692(满)
  • QQ二群:64786792
在线咨询
本站承接WordPress建站仿站、二次开发、主题插件定制等PHP开发服务!

了解详情