If you are using the SVG Support plugin, you will notice that the SVG image URL is incomplete when the WPML Media Translation plugin is active.
An example of how the image URL looks in the translated pages:
With WPML Media Translation enabled: https://my-domain.com/wp-content/uploads/my-logo.svg
Without WPML Media Translation enabled: https://my-domain.com/wp-content/uploads/2022/02/my-logo.svg
As you can see, the problem lies in the wrong path. According to WPML, the cause is the implementation of the plugin SVG support. So far, the problem has not been fixed.
WPML itself offers a workaround for this problem. However, it is advised to make changes to the code of the SVG support plugin. This is not sustainable, because when updating this plugin the made changes could be lost (if the author of the plugin updates exactly this file). Also, it is not a good style and not recommended by WordPress to make changes directly in the code of plugins.
Since I encountered the problem myself and wanted a solution that would work stably even after updates, I wrote my own code for it, which I would like to share below.
Here you will find the solution:
To solve the problem, the following code is added to the WordPress instance. This can be done with the Code Snippets plugin or added to the functions.php of the theme you are using.
Professionals have a separate plugin for such customizations anyway and paste the code there.
function cw_svgs_generate_svg_attachment_metadata( $metadata, $attachment_id ) {
if ( get_post_mime_type( $attachment_id ) != 'image/svg+xml' || FALSE === get_option('uploads_use_yearmonth_folders') )
{
return $metadata;
}
$metadata['file'] = date("Y") . '/' . date("m") . '/' . $metadata['file'];
return $metadata;
}
add_filter( 'wp_generate_attachment_metadata', 'cw_svgs_generate_svg_attachment_metadata', 11, 3 );
Important: The SVGs need to be re-uploaded in WordPress -> Media so that the metadata is created again. Only then do they appear correctly in the translated page (if necessary, trigger automatic translation again).
A few words about the solution
WordPress offers the concept of filters and actions and we take advantage of that here to hook into the code execution of SVG support from the outside.
The cw_svgs_generate_svg_attachment_metadata function is called every time a media file is uploaded to WordPress. If it is not an SVG file or the“Organize my uploads in month and year based folders” option is not enabled in Settings -> Media, the file path should not be changed and the array will be returned the same. Otherwise, year and month are added as path and the array is returned to further execution in SVG Support.
The filename is already in the $metadata array, as we have specified via the priority parameter (value 11) of add_filter, that the function is executed after the wp_generate_attachment_metadata filter function executed by SVG Support (where a lower priority value is used).