When creating an image gallery in WordPress using the default Media Uploader, WordPress wraps the images in a bunch of HTML markup.
How can I overwrite this before it's generated so that I can output the desired markup and change the way the gallery layout is created?
Currently, WordPress is generating the code like this:
<div id="container">
<div src="<?php bloginfo('template_directory'); ?>/images/small.jpg">
<div src="<?php bloginfo('template_directory'); ?>/images/medium.jpg" data-media="(min-width: 400px)"></div>
<div src="<?php bloginfo('template_directory'); ?>/images/large.jpg" data-media="(min-width: 950px)"></div>
<div src="<?php bloginfo('template_directory'); ?>/images/extralarge.jpg" data-media="(min-width: 1200px)"></div>
</div>
Instead of overwriting the gallery shortcode function, a better way is to use the post_gallery filter that is included within that function.
Add this in functions.php
add_filter('post_gallery','customFormatGallery',10,2);
function customFormatGallery($string,$attr){
$output = "<div id=\"container\">";
$posts = get_posts(array('include' => $attr['ids'],'post_type' => 'attachment'));
foreach($posts as $imagePost){
$output .= "<div src='".wp_get_attachment_image_src($imagePost->ID, 'small')[0]."'>";
$output .= "<div src='".wp_get_attachment_image_src($imagePost->ID, 'medium')[0]."' data-media=\"(min-width: 400px)\">";
$output .= "<div src='".wp_get_attachment_image_src($imagePost->ID, 'large')[0]."' data-media=\"(min-width: 950px)\">";
$output .= "<div src='".wp_get_attachment_image_src($imagePost->ID, 'extralarge')[0]."' data-media=\"(min-width: 1200px)\">";
}
$output .= "</div>";
return $output;
}
This is assuming you've set up image sizes for the different sizes you need using https://codex.wordpress.org/Function_Reference/add_image_size