0

I want to return multiple image attachments to my template landing page, but wp_get_attachment_image_src only returns the first image attachment. How come? Thanks in advance

<?php
    /**
     * Custom functions
     */

    function get_images() {
        global $post;
        $size = 'medium';
        $attachments = get_children( array(
                'post_parent' => get_the_ID(),
                'post_status' => null,
                'numberposts'    => -1,
                'post_type' => 'attachment',
                'post_mime_type' => 'image',
                'order' => 'ASC',
                'orderby' => 'menu_order'
            ) );
        if (empty($attachments)) {
            return '';
        }

    foreach ( $attachments as $id  => $attachment ) :
        return wp_get_attachment_image_src($attachment->ID, $size );
    endforeach;

    }

    ?>

1 Answer 1

1

In PHP function can return it's value only one time. After returning value, function dies.

If you want to return multiple values, you have to use array. So your code could look like this:

function get_images() {
    global $post;  // you don't use $post in your code, so it's redundant
    $size = 'medium';
    $attachments = get_children( array(
        'post_parent' => get_the_ID(),
        'post_status' => null,  // ??
        'numberposts'    => -1,  // you should use posts_per_page insted of numberposts
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'order' => 'ASC',
        'orderby' => 'menu_order'
    ) );
    if (empty($attachments)) {
        return '';
    }

    $images = array();
    foreach ( $attachments as $id  => $attachment ) {
        $images[] = wp_get_attachment_image_src($attachment->ID, $size );
    }
    return $images;
}

PS. But it has nothing to do with WordPress...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.