1

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

2
  • 1
    I don't get it... this code works for me... also, you may want to put an extension checker so you don't rename every filetype to JPG
    – brasofilo
    Commented Mar 30, 2012 at 4:29
  • sorry, the original post does warns about the filetype checking...
    – brasofilo
    Commented Mar 30, 2012 at 4:36

1 Answer 1

2

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 );
8
  • Thanks @kaiser!, I am however stuck on this line $post_obj = get_post( (int) $_REQUEST['post_id'] );, which is causing me a Fatal error: Only variables can be passed by reference
    – Charlie
    Commented Mar 30, 2012 at 8:39
  • See update & give it a try. Fun is the reference - ain't got a clue why there should be a reference to the post ID.
    – kaiser
    Commented Mar 30, 2012 at 11:39
  • @Charlie Could you please tell what your problem was, so later readers can profit from that?
    – kaiser
    Commented Mar 30, 2012 at 15:00
  • 1
    sorry for the late reply. Interesting to see you've been using user_nicename. I've been messing around with sanitize_title_with_dashes( $post_obj->post_title ); myself. I've also been messing with the image ext as well using pathinfo, though this only seems to work when using sanitize_file_name instead of wp_handle_upload_prefilter (probably I'll be switching to that instead). Edit: I'm still having some mixed feelings about $random_number, and perhaps go for a modified wp_unique_filename instead (I really do like the dash between the name and the number :))
    – Charlie
    Commented Apr 7, 2012 at 13:37
  • 2
    Thanks again. For what it's worth, this is what I'm currently having (mostly based on your previous answer): gist.github.com/2329856
    – Charlie
    Commented Apr 7, 2012 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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