Skip to content

Instantly share code, notes, and snippets.

@vitaliikaplia
Last active April 21, 2022 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitaliikaplia/be367e41ce0ba44dc1eb74ae9a6a00a5 to your computer and use it in GitHub Desktop.
Save vitaliikaplia/be367e41ce0ba44dc1eb74ae9a6a00a5 to your computer and use it in GitHub Desktop.
Rename file on upload inside post
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment