Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Here's the function I use for WP to rename images during upload on the fly and set the image's filename to match the post slug.

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);

I want to keep the original filename adding $ post_slug

[thread_title]-[original_filename].ext

share|improve this question
add comment

1 Answer

You can try to replace

$arr['name'] = $post_slug . '-' . $random_number . '.jpg';

with

$arr['name'] = $post_slug . '-' . $arr['name'];

to get the file format [post_slug]-[original_filename].ext.

Update:

Here is an example of the $arr structure for an image with the filename car.png :

 Array
(
    [name] => car.png
    [type] => image/png
    [tmp_name] => /tmp/phpJKhCwI
    [error] => 0
    [size] => 5868
)

To get the [post_slug].ext format, one could use this:

$arr['name'] = $post_slug . '.' . pathinfo( $arr['name'], PATHINFO_EXTENSION );

When the post title is My favorite car it becomes:

 Array
(
    [name] => my-favorite-car.png
    [type] => image/png
    [tmp_name] => /tmp/phpJKhCwI
    [error] => 0
    [size] => 5868
)

When more than one image is uploaded with the same filename, the uploaded image filename will become:

my-favorite-car.png  (1. upload)
my-favorite-car1.png (2. upload)
my-favorite-car2.png (3. upload)
...
share|improve this answer
    
thx excellent!!!! –  Daniela Mar 31 '13 at 14:58
    
This seems obvious, but: how would I modify this to get [post_slug].ext? –  pereyra Aug 27 '13 at 22:03
    
@pereyra, please check out the updated answer. –  birgire Aug 28 '13 at 2:43
    
@birgire, thank you very much. –  pereyra Aug 29 '13 at 5:02
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.