如何使用wp_Get_Attach_Image_src返回多个图像附件

时间:2014-04-23 作者:user50719

我想将多个图像附件返回到模板登录页,但wp\\u get\\u attachment\\u image\\u src只返回第一个图像附件。怎么会这样?提前感谢

<?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 个回复
SO网友:Krzysiek Dróżdż

在PHP中,函数只能返回一次它的值。返回值后,函数终止。

如果要返回多个值,必须使用数组。因此,您的代码可能如下所示:

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;
}
附言,但这与WordPress无关。。。

结束