Source Code for /public/04-includes-and-functions/captioned-image-function.php

<?php
/**
 * Renders a captioned image. Takes the following parameters:
 * - $url: The URL of the image to display.
 * - $alt: The alt text for the image.
 * - $caption: The caption to be displayed below the image.
 * - $max_width: The maximum width of the image in pixels;
 *               optional - defaults to 100 (pixels).
 */
function cap_img( $url, $alt, $caption, $max_width = 80 ) {
  ?>
  <figure>
    <a href="<?php echo $url; ?>">
      <img src="<?php echo $url; ?>"
          alt="<?php echo $alt; ?>"
        style="max-width: <?php echo $max_width; ?>px;
               height: auto;">
    </a>
    <figcaption><?php echo $caption; ?></figcaption>
  </figure>
  <?php
}
?>

<p>
  Things in my fruitbowl:
</p>

<div class="gallery">
  <?php
  /* Now we'll use our function to display a gallery: */
  cap_img( '/img/fruit/apple.jpg', 'A red apple',
          'From the tree in my back yard.' );

  cap_img( '/img/fruit/bananas.jpg', 'Two ripe bananas',
          "They're my favorite fruit." );

  cap_img( '/img/fruit/plums.webp', 'A bowl of purple plums',
          'I enjoy making jam every Autumn.' );

  cap_img( '/img/fruit/kiwi.jpg', 'A halved kiwi fruit',
          'I wish these grew in my part of the world.' );
  ?>
</div>