这两种都是可能的。
以下是文档中的示例代码:
<?php
$wp_filetype = wp_check_filetype(basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
\'guid\' => $wp_upload_dir[\'baseurl\'] . _wp_relative_upload_path( $filename ),
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_title\' => preg_replace(\'/\\.[^.]+$/\', \'\', basename($filename)),
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
$attach_id = wp_insert_attachment( $attachment, $filename, 37 );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . \'wp-admin/includes/image.php\');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
?>
更改上载目录要更改上载目录,您需要使用
upload_dir
滤器
Yoast has a pretty good tutorial 关于如何做到这一点。
add_filter(\'upload_dir\', \'my_upload_dir\');
$upload = wp_upload_dir();
remove_filter(\'upload_dir\', \'my_upload_dir\');
function my_upload_dir($upload) {
$upload[\'subdir\'] = \'/sub-dir-to-use\' . $upload[\'subdir\'];
$upload[\'path\'] = $upload[\'basedir\'] . $upload[\'subdir\'];
$upload[\'url\'] = $upload[\'baseurl\'] . $upload[\'subdir\'];
return $upload;
}