I am trying to add the post ID and the post title to all uploaded images in my WordPress posts.
I have already found a function, which renames my images like a charm, but I cannot get the post id and post title. What am I doing wrong?
function new_filename($filename, $filename_raw) {
global $post;
$post_id = $post->ID;
$post_slug = $post->post_name;
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$new = $post_id . $post_slug . $ext;
if( $new != $filename_raw ) {
$new = sanitize_file_name( $new );
}
return $new;
}
add_filter('sanitize_file_name', 'new_filename', 10, 2);
Thank you.