After trying to add a function to publish_post
and creating a lot of unnecessary files I tried to blemish kaisers function to fit my needs.
function modify_uploaded_file_names( $image ) {
// Use part of the post or user object to rename the image
get_currentuserinfo();
global $post, $current_user;
// 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 ( isset( $_REQUEST['post_id'] ) ) {
// get the ID
$post_id = absint( $_REQUEST['post_id'] );
// get the post OBJECT
$post_obj = get_post( $post_id );
// get the post slug
$post_slug = sanitize_title($post_obj->post_title);
// get the author
$author = sanitize_title( get_the_author_meta( 'display_name', $post_obj->post_author ) );
switch( $image['type'] ) {
case 'image/jpeg' :
$suffix = 'jpg';
break;
case 'image/png' :
$suffix = 'png';
break;
case 'image/gif' :
$suffix = 'gif';
break;
}
// if we found a slug
if ( $post_slug )
$image['name'] = "{$author}-{$post_slug}-{$random_number}.{$suffix}";
}
else {
$image_name = str_place( ' ', '-', strtolower( $current_user->data->user_nicename ) );
$image['name'] = $image_name . '-' . $file['name'];
}
return $image;
}
// Only one arg, so 4th attr not needed - Priority set to later 20
add_filter( 'wp_handle_upload_prefilter', 'my_modify_uploaded_file_names', 20 );
There are only some small changes
- replaced
$post_obj->post_name
withsanitize_title($post_obj->post_title)
since post_name only was present in my tests when the post already was saved. - deleted the random-numbers, cause
wp_handle_upload
uses wp_unique_filename() anyway. - Added the author-name to the file-name, but that’s just something I need.