I need to rename images uploaded by the user when they post on my site.
I have a code that works perfectly to save the image and make it part of the post. But I want the images to be renamed to have the title of the post in their filename.
The code I have:
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$img_id01 = media_handle_upload( 'img_main', $postID );
update_post_meta($postID, 'img_id01', $img_id01);
I need to rename images uploaded by the user when they post on my site.
I have a code that works perfectly to save the image and make it part of the post. But I want the images to be renamed to have the title of the post in their filename.
The code I have:
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$img_id01 = media_handle_upload( 'img_main', $postID );
update_post_meta($postID, 'img_id01', $img_id01);
I cannot test this because I don't have your code, but maybe you can get some ideas from it:
add_filter( 'wp_unique_filename', 'custom_image_name', 10, 2 );
$img_id01 = media_handle_upload( 'img_main', $postID );
remove_filter( 'wp_unique_filename', 'custom_image_name', 10, 2 );
function custom_image_name( $filename, $ext ) {
global $postID;
$post = get_post( $postID );
return $filename . '-' . $post->post_name . $ext;
}
This is not very elegant because $postID
needs to be in a global scope, but it might do the job.
wp_unique_filename()
, which in itself has a filterwp_unique_filename
applied before returning the value. – Hans Commented Sep 26, 2018 at 16:55