Jack Cash
Jack Cash

Reputation: 149

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?

Upvotes: 3

Views: 30358

Answers (3)

Maulik patel
Maulik patel

Reputation: 2432

<?php if (has_post_thumbnail( $post->ID ) ): ?>
  <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
  <div id="custom-bg" style="background-image: url('<?php echo $image[0]; ?>')">

  </div>
<?php endif; ?>

Upvotes: -1

WPExplorer
WPExplorer

Reputation: 119

If you just want to link to the original full image it's better to simply use "wp_get_attachment_url" - https://developer.wordpress.org/reference/functions/wp_get_attachment_url/

The wp_get_attachment_image_src function will run code you don't need and return extra details you don't need making your code less efficient.

Upvotes: 0

Mathew Tinsley
Mathew Tinsley

Reputation: 6976

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.

Upvotes: 15

Related Questions