Issues renaming images during upload

Sent Header

The following error simply states that the error message was output directly (sent header)

Warning: Cannot modify header information - headers already sent by (output started at /home/lorem/public_html/clients/ipsum/wp-content/plugins/myplugin/test.php:504) in /home/lorem/public_html/clients/ipsum/wp-includes/pluggable.php on line 864

PHP Error notice

Notice: Undefined variable: post_id in /home/lorem/public_html/clients/ipsum/wp-content/plugins/myplugin/test.php on line 18

$_REQUEST is a combination of a lot of things, and it also takes stuff from $_POST and $_GET. So the 1st thing I’d try is to drop your if/else statement and replace it with a simple $_REQUEST['post_id'].

Some other ideas

I understand, that the idea behind the snippet is that you also modify images that are just selected and not uploaded exclusively for that post. Else I can’t understand why all this is necessary. Therefore I’d try the following:

function modify_uploaded_file_names( $image ) 
{
    // Use part of the post or user object to rename the image
    get_currentuserinfo();
    global $post, $current_user;

    $random_number = rand( 10000, 99999 );

    // 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 = $post_obj->post_name;

        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'] = "{$post_slug}-{$random_number}.{$suffix}";
    }
    else 
    {
        $image_name    = str_place( ' ', '-', strtolower( $current_user->data->user_nicename ) );
        $image['name'] = "{$image_name}-{$random_number}.jpg";
    }

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

Leave a Comment