Search code examples
phpwordpress

Get the Wordpress attachment image url


I am trying to display all the images attached to a wordpress post and link the image to the source of the image to open it in a light box. I am using the following code:

if (have_posts())
{
    while (have_posts())
    {
        the_post();    
        $args = array(
            'orderby' => 'title',
            'order' => 'ASC',
            'post_type' => 'attachment',
            'numberposts' => -1,
            'post_status' => null,
            'post_parent' => $post->ID,
            'exclude' => get_post_thumbnail_id()
        );
        $attachments = get_posts( $args );
        if ($attachments)
        {
            foreach ($attachments as $attachment)
            {
                ?>
                <div id="image">
                    <a rel="lightbox" href="<?php /* ??? */ ?>">
                    <?php echo wp_get_attachment_image ($attachment->ID, 'full'); ?>
                    </a>
                </div>
                <?php
            }
        }
    }
}

I have tried many things where the ??? but i can't seem to retrieve just the source url.

Can anyone provide some insight?


Solution

  • Use wp_get_attachment_image_src

    https://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src

    This:

    wp_get_attachment_image_src( $attachment->ID, 'full' );
    

    should return an array with the following elements

    [0] => url
    [1] => width
    [2] => height
    [3] => boolean: true if $url is a resized image, false if it is the original or if no image is available.