TransWikia.com

How to change the output of gallery shortcode

WordPress Development Asked by Alex Maiburg on December 8, 2021

I would like to add the media description as a data-attribute to each image of the gallery. All the other answers favour the solution to copy the whole code from media.php to functions.php and change it there. But isn’t there a more intelligent way?

It’s way to much code duplication in order to change one single line of code!

One Answer

If anybody is interested: I managed it to add a data attribute to the article thumbnail with following filter:

function post_thumbnail_add_data_attribute( $input, $post_image_id ) {
  $caption = wptexturize(get_post(get_post_thumbnail_id())->post_excerpt);
  $substitute = is_home() ? "<img" : "<img data-description="" . $caption . """;

  return str_replace("<img", $substitute, $input);
}

add_filter('post_thumbnail_html', 'post_thumbnail_add_data_attribute', 10, 3 );

For the gallery I followed the advice to remove the gallery shortcode...

remove_shortcode('gallery');

and then to add a customized gallery function to the functions.php...

add_shortcode('gallery', 'my_gallery');

which contains the tiny customization...

// Add the caption of images in a gallery as the name attribute in order to fetch it with jQuery lightbox
$output = str_replace('<img', '<img data-description="' . wptexturize($attachment->post_excerpt) . '"', $output);

Answered by Alex Maiburg on December 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP