Issues renaming images during upload

The main reason for adding this snippet is all about SEO. The people I sometimes make websites for often aren’t that savvy with WP and tend to upload their stuff just as is. As these are often media related websites I try to help them a bit by automatically renaming their uploads from DSC_0010.JPG to my-optimized-post-title-001.JPG, etc.


I’m currently using this snippet which renames my files during upload.

add_filter( 'wp_handle_upload_prefilter', 'my_modify_uploaded_file_names', 1, 1 );
function my_modify_uploaded_file_names( $image_name ) {
  // get the parent post id, if there is one
  if ( isset( $_GET['post_id'] ) ) {
    $post_id = $_GET['post_id'];
  } elseif ( isset( $_POST['post_id'] ) ) {
    $post_id = $_POST['post_id'];
  }
  // 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 ( 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 );
      $image_name['name'] = $post_slug . '-' . $random_number . '.jpg';
    }
  }
  return $image_name;
}

However, when having WP_DEBUG set to true it giving me this error:

Notice: Undefined variable: post_id in /home/lorem/public_html/clients/ipsum/wp-content/plugins/myplugin/test.php on line 18
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

From the question linked to people tell it’s missing the $_GET variables. Something I’m unable to solve myself…

Does someone know perhaps on how to get this script working again? (or know perhaps a similar solution?)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x