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?)
Sent Header
The following error simply states that the error message was output directly (sent header)
PHP Error notice
$_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 yourif/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: