您将希望连接到wp\\u handle\\u upload\\u prefilter过滤器(我找不到任何文档,但看起来很简单)。我在当地尝试过这个方法,它似乎对我有效:
function wpsx_5505_modify_uploaded_file_names($arr) {
// Get the parent post ID, if there is one
if( isset($_REQUEST[\'post_id\']) ) {
$post_id = $_REQUEST[\'post_id\'];
} else {
$post_id = false;
}
// Only do this if we got the post ID--otherwise they\'re probably in
// the media section rather than uploading an image from a post.
if($post_id && is_numeric($post_id)) {
// Get the post slug
$post_obj = get_post($post_id);
$post_slug = $post_obj->post_name;
// If we found a slug
if($post_slug) {
$random_number = rand(10000,99999);
$arr[\'name\'] = $post_slug . \'-\' . $random_number . \'.jpg\';
}
}
return $arr;
}
add_filter(\'wp_handle_upload_prefilter\', \'wpsx_5505_modify_uploaded_file_names\', 1, 1);
在我的测试中,似乎只有启用了相当长的永久链接后,帖子才有一个slug,所以我添加了一个检查,以确保在重命名文件之前有一个slug。您还需要考虑检查文件类型,我在这里没有做这件事——我只是假设它是jpg。
EDIT
根据注释中的要求,此附加功能会更改上载图像的某些元属性。但似乎不允许您设置ALT文本,并且由于某种原因,您设置为“标题”的值实际上被指定为描述。你得胡闹。我在函数wp\\u read\\u image\\u metadata()中找到了此筛选器,该函数位于wp admin/includes/image中。php。媒体上载和wp\\u generate\\u attachment\\u元数据功能依赖于此从图像中提取元数据。如果你想了解更多,可以看看那里。
function wpsx_5505_modify_uploaded_file_meta($meta, $file, $sourceImageType) {
// Get the parent post ID, if there is one
if( isset($_REQUEST[\'post_id\']) ) {
$post_id = $_REQUEST[\'post_id\'];
} else {
$post_id = false;
}
// Only do this if we got the post ID--otherwise they\'re probably in
// the media section rather than uploading an image from a post.
if($post_id && is_numeric($post_id)) {
// Get the post title
$post_title = get_the_title($post_id);
// If we found a title
if($post_title) {
$meta[\'title\'] = $post_title;
$meta[\'caption\'] = $post_title;
}
}
return $meta;
}
add_filter(\'wp_read_image_metadata\', \'wpsx_5505_modify_uploaded_file_meta\', 1, 3);
Edited 04/04/2012 to pull post ID from the REQUEST obj rather than checking the GET and POST successively. Based on suggestions in the comments.