rename image file using post id in wordpress programmatically

  1. Open your theme's functions.php file.

  2. Add the following code to rename the image file using the post ID when a new media is uploaded:

function rename_uploaded_file($filename) {
    global $post;

    // Get the post ID
    $post_id = $post->ID;

    // Get the file extension
    $file_extension = pathinfo($filename, PATHINFO_EXTENSION);

    // Generate the new filename using the post ID
    $new_filename = $post_id . '.' . $file_extension;

    return $new_filename;
}

add_filter('sanitize_file_name', 'rename_uploaded_file', 10);

This code defines a function rename_uploaded_file that takes the original filename as input, extracts the file extension, and generates a new filename using the post ID. The sanitize_file_name filter is then hooked to this function with a priority of 10.

  1. Save the functions.php file.

  2. Upload a new media file in WordPress.

Now, the uploaded image file will be renamed using the post ID.