PurabTech is technical blog for Programmer and Coders
Change image name to wordpress post slug during upload
WordPress tutorial, Change image name to wordpress post slug during upload. If you want to rename files during upload and set their names to the post slug.
If you want to rename files during upload and set their names to the post slug the files are being attached to, plus some random characters (a simple incremental counter will be just fine) to make the filenames different.
Change image name to wordpress post slug during upload
Change image name to wordpress post slug during upload
In other words, if you are uploading/attaching images to the post whose page slug is “test-page-slug”, i’d like for the images to be renamed on the fly to test-page-slug-[C].[original_extension] — test-page-slug-1.jpg, test-page-slug-2.jpg etc (no matter what the original filenames were).
This is very easy. You just need to use following hook in functions.php file.
This is very easy.
if you have pretty permalinks enabled, so I’ve added a check to make sure there is a slug before renaming the file. You’ll also want to consider checking the file type, which I haven’t done here–I’ve just assumed it’s a jpg.
I googled for this many times till i finally found your page
Can you please tell me why im getting this error after modifying functions.php in /wp-includes/functions.php
Fatal error: Call to undefined function add_filter()
This is an excellent function Purab. However I added a few lines to dynamically get the file extension. I also didn’t use the random number, instead I took advantage of WP 4.x function that automatically increment and adds a numerical value to the filename if a similar name is detected.
very nice code trick..great.
thank youvery much
I googled for this many times till i finally found your page
Can you please tell me why im getting this error after modifying functions.php in /wp-includes/functions.php
Fatal error: Call to undefined function add_filter()
Thanks for this post, does exactly what I needed. How to check for file extension though?
Also how to automatically set the ‘Alt’ value on the image upload dialog to be the value of the Post title?
hi
its not worked for me?
whats wrong?
did you added this code in functions.php file exactly as shown.
Hi,
Didn’t worked for me, i simply added this coded in my functions.php and its giving an error while image upload
I will verify this..
Didn’t worked for me in 4.6.1 version
plz edit it i need
This is an excellent function Purab. However I added a few lines to dynamically get the file extension. I also didn’t use the random number, instead I took advantage of WP 4.x function that automatically increment and adds a numerical value to the filename if a similar name is detected.
$fileinfo = pathinfo( $image_name[‘name’] );
$fileext = empty( $fileinfo[‘extension’] ) ? ” : ‘.’ . $fileinfo[‘extension’];
$image_name[‘name’] = $post_slug . ‘-‘ . $fileext;
WP 4.6.1
PHP 5.6
MySQL 5.6