The img_caption_shortcode
hook in WordPress is a filter hook that allows developers to modify the output of the caption shortcode for images.
When you add an image to your WordPress post or page and include a caption, WordPress automatically generates a caption shortcode to display the image with its caption. By using the img_caption_shortcode
hook, you can customize the HTML markup or add additional functionality to the generated caption output.
This hook is particularly useful if you want to style the caption differently, add custom classes or attributes to the caption container, or even add extra elements such as social sharing buttons.
Here’s an example usage of the img_caption_shortcode
hook:
function custom_img_caption_shortcode($output, $attr, $content) {
// Modify the caption output HTML
$output = '<div class="custom-caption">' . $content . '</div>';
// Return the modified output
return $output;
}
add_filter('img_caption_shortcode', 'custom_img_caption_shortcode', 10, 3);
In this example, we define a custom function custom_img_caption_shortcode
that accepts three parameters: $output
, $attr
, and $content
. The $output
parameter contains the default HTML markup for the caption, $attr
contains any attributes passed to the caption shortcode, and $content
holds the content of the caption.
Within the function, we modify the $output
variable to encapsulate the caption content within a <div>
element with a custom class called "custom-caption". Finally, we return the modified $output
to WordPress using the return
statement.
By adding the add_filter
function, we hook our custom function custom_img_caption_shortcode
to the img_caption_shortcode
hook with a priority of 10. This ensures that our function is called and modifies the caption output before it is displayed on the front end.
With this example, you can easily customize the caption markup for images in WordPress and tailor it to your website’s design and requirements.