Using WordPress ‘img_caption_shortcode()’ PHP function

The img_caption_shortcode WordPress PHP function builds the Caption shortcode output.

Usage

img_caption_shortcode($attr, $content = '');

Parameters

  • $attr array (Required): Attributes of the caption shortcode:
    • id string: ID of the image and caption container element, i.e. <figure> or <div>.
    • caption_id string: ID of the caption element, i.e. <figcaption> or <p>.
    • align string: Class name that aligns the caption. Default ‘alignnone’. Accepts ‘alignleft’, ‘aligncenter’, ‘alignright’, ‘alignnone’.
    • width int: The width of the caption, in pixels.
    • caption string: The caption text.
    • class string: Additional class name(s) added to the caption container.
  • $content string (Optional): Shortcode content. Default: ”

More information

See WordPress Developer Resources: img_caption_shortcode

Examples

Basic Usage

Add a captioned image to your post or page using the img_caption_shortcode function.

// Use the img_caption_shortcode function to create a captioned image
echo do_shortcode('
<img src="image_url.jpg" alt="Sample Image" />
This is a captioned image.
');

Add a Custom Class

Add a custom CSS class to style the captioned image.

// Add a custom class to the caption container
echo do_shortcode('
<img src="image_url.jpg" alt="Sample Image" />
Caption with a custom class.
');

Change Caption Alignment

Display a captioned image with different alignments.

// Align the caption to the left
echo do_shortcode('
<img src="image_url.jpg" alt="Sample Image" />
Caption aligned left.
');

Custom Caption ID

Set a custom ID for the caption element.

// Set a custom ID for the caption element
echo do_shortcode('
<img src="image_url.jpg" alt="Sample Image" />
Caption with a custom ID.
');

No Caption

Display an image without a caption using an empty caption attribute.

// Display an image without a caption
echo do_shortcode(' <img src="image_url.jpg" alt="Sample Image" />');