I want change the WordPress gallery html layout, By default, the output of HTML is as follows:
<div id="gallery-1" class="gallery galleryid-184 gallery-columns-3 gallery-size-thumbnail">
<dl class="gallery-item">
<dt class="gallery-icon landscape">
<a href="http://localhost:8888/mmysite/tesla-2/"><img src="http://localhost:8888/mmysite/wp-content/uploads/2021/03/tesla.png" class="attachment-thumbnail size-thumbnail" alt="" loading="lazy" width="150" height="110"></a>
</dt>
</dl>
<dl class="gallery-item">
<dt class="gallery-icon landscape">
<a href="http://localhost:8888/mmysite/3/"><img src="http://localhost:8888/mmysite/wp-content/uploads/2021/03/3.gif" class="attachment-thumbnail size-thumbnail" alt="" loading="lazy" width="150" height="58"></a>
</dt>
</dl>
<br style="clear: both">
</div>
And I want change to this:
<div class="mihan-gallery">
<a class="mihangitem" href="http://localhost:8888/mmysite/wp-content/uploads/2021/03/tesla.png"><img src="http://localhost:8888/mmysite/wp-content/uploads/2021/03/tesla.png" alt="" title=""/></a>
<a class="mihangitem" href="http://localhost:8888/mmysite/wp-content/uploads/2021/03/3.gif"><img src="http://localhost:8888/mmysite/wp-content/uploads/2021/03/3.gif" alt="" title=""/></a>
<div class="clear"></div>
</div>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I find a solution for this:
// Customise the WordPress gallery html layout
add_filter('post_gallery','customFormatGallery',10,2);
function customFormatGallery($string,$attr){
$output = "<div class="mihan-gallery">";
$posts = get_posts(array('include' => $attr['ids'],'post_type' => 'attachment'));
foreach($posts as $imagePost){
$output .= "<a class="mihangitem" href='".wp_get_attachment_image_src($imagePost->ID, 'mihan-large')[0]."'><img src='".wp_get_attachment_image_src($imagePost->ID, 'mihan-medium')[0]."'></a>";
}
$output .= "<div class="clear"></div></div>";
return $output;
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0