Get WooCommerce product gallery image caption

Quick Question for someone who knows their wordpress.

I’m using the following code to show the WC product gallery on the product page (in the right order).

Read More

Someone can quickly point me in the direction of including the image caption between the <p>‘s?

global $product;
$attachment_ids = $product->get_gallery_attachment_ids();

echo '<div class="flexslider"><ul class="slides">';
foreach( $attachment_ids as $attachment_id ) 
{
echo '<li>';
  echo "<img src=".$image_link = wp_get_attachment_url( $attachment_id, 'large').">";
  echo '<p>';
  echo '</p>';
  echo '</li>';
}
echo '</ul></div>';

Related posts

Leave a Reply

2 comments

  1. Here is the way to achieve it:

    First of all add below code to your theme’s functions.php :

    function wp_get_attachment( $attachment_id ) {
    
        $attachment = get_post( $attachment_id );
        return array(
            'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
            'caption' => $attachment->post_excerpt,
            'description' => $attachment->post_content,
            'href' => get_permalink( $attachment->ID ),
            'src' => $attachment->guid,
            'title' => $attachment->post_title
        );
    }
    

    After that you can use it like :

    $attachment_meta = wp_get_attachment($attachment_id);
    echo $attachment_meta['caption'];
    

    So your final code would be :

    global $product;
    $attachment_ids = $product->get_gallery_attachment_ids();
    
    echo '<div class="flexslider"><ul class="slides">';
    foreach( $attachment_ids as $attachment_id ) 
    {
        echo '<li>';
        echo "<img src=".$image_link = wp_get_attachment_url( $attachment_id, 'large').">";
        echo '<p>';
        $attachment_meta = wp_get_attachment($attachment_id);
        echo $attachment_meta['caption'];
        echo '</p>';
        echo '</li>';
    }
    echo '</ul></div>';
    

    Source: wordpress topic forum