Add Snippet To Project
Are you annoyed by the inline width that automatically gets added to your image caption in WordPress? It’s a common complaint amongst WordPress users, as it often hampers the aesthetic appearance of your website and is hard to remove. But fortunately, we’ve got a solution. In this article, we will guide you step-by-step through the process to remove the caption inline width in WordPress, keeping your website layout clean and professional.
function wpturbo_remove_caption_inline_width($dummy, $attr, $content) {
if (isset($attr['width'])) unset($attr['width']);
if (isset($attr['height'])) unset($attr['height']);
return $content;
}
add_filter('img_caption_shortcode', 'wpturbo_remove_caption_inline_width', 10, 3);
The given code snippet is a WordPress function that is defined in PHP. The function wpturbo_remove_caption_inline_width() is used to remove the inline width that is automatically added by WordPress to image captions.
In this function, three parameters are passed: $dummy, $attr and $content. The $dummy parameter is used here to accept the first output from the ‘img_caption_shortcode’ filter – but we will not be using this parameter in our function.
function wpturbo_remove_caption_inline_width($dummy, $attr, $content) {
The $attr parameter is an associative array containing all the attributes defined in the caption shortcode. This can include, amongst other things, the width and height values attached to the image caption.
Let’s take a look at this block:
if (isset($attr['width'])) unset($attr['width']);
if (isset($attr['height'])) unset($attr['height']);
In this block, we are checking if the $attr array has ‘width’ and/or ‘height’ values. The isset() function in PHP is used to check whether a variable is set and is not NULL. If ‘width’ and/or ‘height’ exist, they are removed from the $attr array using the unset() function. The unset() function destroys the specified variables.
Next, the function returns the $content parameter.
return $content;
This is the actual HTML content of the caption shortcode. As we’ve not made any changes to the $content, it’s returned as it was received.
Last, but not least is the add_filter() function call:
add_filter('img_caption_shortcode', 'wpturbo_remove_caption_inline_width', 10, 3);
This part of the function is utilizing a WordPress specific function called add_filter. It’s used to hook ('img_caption_shortcode') a custom function (wpturbo_remove_caption_inline_width) into a specific filter action (in this case img_caption_shortcode). The img_caption_shortcode action is fired whenever an image caption shortcode is processed, which enables custom functionality to be added. The ’10’ refers to the priority within all functions hooked to this filter, with lower numbers corresponding with earlier execution and the ‘3’ is referring to the number of accepted parameters – in our case: $dummy, $attr and $content.
