[wp-trac] [WordPress Trac] #36270: Allow filtering of the final HTML output of media related shortcodes
WordPress Trac
noreply at wordpress.org
Wed Feb 5 06:34:03 UTC 2025
#36270: Allow filtering of the final HTML output of media related shortcodes
-------------------------+------------------------------
Reporter: gnotaras | Owner: (none)
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Media | Version: 4.7.2
Severity: normal | Resolution:
Keywords: needs-patch | Focuses:
-------------------------+------------------------------
Comment (by sahilgidwani):
Hi @gnotaras ,
You can use existing WordPress filters to modify the output without
overriding the entire function. The two key filters you need to use are:
1. `img_caption_shortcode` – Filters the output of the `caption`
shortcode.
2. `post_gallery` – Filters the output of the `gallery` shortcode.
=== Example: Modifying the Caption Shortcode Output ===
To wrap `<figure>` with an extra `<div class="custom-wrapper">`:
{{{#!php
<?php
add_filter('img_caption_shortcode', function ($output, $attr, $content) {
if ($output !== '') {
return $output;
}
// Generate the default caption HTML
$caption_id = isset($attr['caption_id']) ? ' id="' .
esc_attr($attr['caption_id']) . '"' : '';
$class = 'wp-caption ' . esc_attr($attr['align'] ?? '') . ' ' .
esc_attr($attr['class'] ?? '');
$caption = esc_html($attr['caption'] ?? '');
$html = '<div class="custom-wrapper">';
$html .= sprintf(
'<figure class="%s">%s<figcaption%s>%s</figcaption></figure>',
$class,
do_shortcode($content),
$caption_id,
$caption
);
$html .= '</div>';
return $html;
}, 10, 3);
}}}
=== Example: Modifying the Gallery Shortcode Output ===
To wrap the `gallery` with `<section class="custom-gallery">`:
{{{#!php
<?php
add_filter('post_gallery', function ($output, $attr, $instance) {
$output = '<section class="custom-gallery">' .
gallery_shortcode($attr) . '</section>';
return $output;
}, 10, 3);
}}}
This way, you avoid overriding core functions and can customize media-
related shortcodes dynamically.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/36270#comment:6>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list