Using WordPress ‘image_add_caption()’ PHP function

The image_add_caption() WordPress PHP function adds an image shortcode with a caption to the editor.

Usage

image_add_caption($html, $id, $caption, $title, $align, $url, $size, $alt = '');

Parameters

  • $html (string) – The image HTML markup to send.
  • $id (int) – Image attachment ID.
  • $caption (string) – Image caption.
  • $title (string) – Image title attribute (not used).
  • $align (string) – Image CSS alignment property.
  • $url (string) – Image source URL (not used).
  • $size (string) – Image size (not used).
  • $alt (string, optional) – Image alt attribute (not used). Default: ”.

More information

See WordPress Developer Resources: image_add_caption()

Examples

Adding a caption to an image

This example demonstrates how to add a caption to an image using the image_add_caption() function.

// Define the image HTML markup
$image_html = '<img src="path/to/image.jpg" alt="Sample Image" />';

// Define the image attachment ID
$image_id = 123;

// Define the image caption
$image_caption = 'A beautiful landscape.';

// Define the image alignment
$image_align = 'center';

// Call the image_add_caption() function
$shortcode = image_add_caption($image_html, $image_id, $image_caption, '', $image_align, '', '', '');

// Output the shortcode
echo $shortcode;

Adding a left-aligned image with caption

This example demonstrates how to add a left-aligned image with a caption using the image_add_caption() function.

$image_html = '<img src="path/to/image.jpg" alt="Sample Image" />';
$image_id = 124;
$image_caption = 'A lovely sunset.';
$image_align = 'left';

$shortcode = image_add_caption($image_html, $image_id, $image_caption, '', $image_align, '', '', '');
echo $shortcode;

Adding a right-aligned image with caption

This example demonstrates how to add a right-aligned image with a caption using the image_add_caption() function.

$image_html = '<img src="path/to/image.jpg" alt="Sample Image" />';
$image_id = 125;
$image_caption = 'A peaceful beach.';
$image_align = 'right';

$shortcode = image_add_caption($image_html, $image_id, $image_caption, '', $image_align, '', '', '');
echo $shortcode;

Adding a centered image without caption

This example demonstrates how to add a centered image without a caption using the image_add_caption() function.

$image_html = '<img src="path/to/image.jpg" alt="Sample Image" />';
$image_id = 126;
$image_caption = '';
$image_align = 'center';

$shortcode = image_add_caption($image_html, $image_id, $image_caption, '', $image_align, '', '', '');
echo $shortcode;