Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress get image url (currently using wp_get_attachment_url)

Having a little trouble in getting image attachment urls in wordpress. This is my code so far:

<?php // find images attached to this post / page.
            global $post;
            $thumb_ID = get_post_thumbnail_id( $post->ID );
            $args = array(
                'post_type' => 'attachment',
                'post_mime_type' => 'image',
                'numberposts' => -1,
                'orderby' => 'menu_order',
                'order' => 'ASC',
                'exclude' => $thumb_ID,
                'post_parent' => $post->ID
            );
            $images = get_posts($args);
            ?>

            <?php // Loop through the images and show them

            if($images)
            {
            foreach($images as $image)  
            {

            echo  wp_get_attachment_image_url($image->ID, $size='attached-image');

            }
            }

?>

Which returns nothing. If I swap out wp_get_attachment_image_url($image->ID, $size='attached-image'); for wp_get_attachment_image($image->ID, $size='attached-image'); this works fine, but brings in the image rather than just the url.

like image 930
Alfazo Avatar asked Apr 30 '12 19:04

Alfazo


Video Answer


1 Answers

The following code will loop through all image attachments and output the src url. Note that there are two methods shown, depending on your need.

<?php

    global $post;
    $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_mime_type' => 'image', 'post_status' => null, 'post_parent' => $post->ID ); 
    $attachments = get_posts($args);
    if ($attachments) {
            foreach ( $attachments as $attachment ) {
                    // Method #1: Allows you to define the image size
                    $src = wp_get_attachment_image_src( $attachment->ID, "attached-image");
                    if ($src) {echo $src[0];}
                    // Method #2: Would always return the "attached-image" size
                    echo $attachment->guid;
            }
    }

?>
like image 136
random_user_name Avatar answered Sep 28 '22 05:09

random_user_name