Documentation, Reference Materials and Tutorials for Envira Gallery
How to set Captions as Image Filenames
Would you like to automatically set captions as image filenames?
With Envira, you can automatically set image captions to match filenames. This makes it easy to add captions without extra effort.
You can do this by simply adding simple code snippets. Follow our step-by-step guide to set it up quickly.
Heads up!
This article contains PHP, CSS, and/or JavaScript to customize our plugin. We offer this code as a courtesy but don’t provide support for additional code customizations or 3rd party development.
Adding the Code Snippet
To automatically set captions as image filenames, just add the following code to your site.
/* Envira - Set Captions to Image Filenames
*
* @link https://enviragallery.com/docs/how-to-set-captions-as-image-filenames/
*/
function envira_set_captions_image_filenames( $data ) {
// Iterate through each gallery image
foreach ( $data['gallery'] as $key => $item ) {
$filename = $item['src'];
$data['gallery'][ $key ]['caption'] = basename( preg_replace('/\.[^.\s]{3,4}$/', '', $filename) );
}
return $data;
}
add_filter( 'envira_gallery_pre_data', 'envira_set_captions_image_filenames' );
The referenced code above will automatically set your filename as the image caption but remove the file extension.
After adding the code, check your gallery images on the frontend. You should see the caption below the image that matches with the filename.
FAQs
Q: Why isn’t the filename showing in my caption when I edit the image?
A: Envira won’t update your database entry for the caption, but when you enable captions to show under the image or in the lightbox, this plugin will automatically pull that filename for your image caption.