首页 > 解决方案 > 如何用逗号列出 wordpress 附件 URL?

问题描述

我的帖子上有一个图片库字段,我可以在其中添加多张图片。

我需要在里面用逗号列出附件 urldata-thumb"url1,url2,url3"如何在下面的函数中用逗号分隔拇指?

function multi_thumbs_array(){
    global $post;
        $images = get_post_meta( $post->ID, 'images', true );
      if( $images ):
        $size = 'thumbnail';
            foreach( $images as $image ):
              echo wp_get_attachment_image_url($image, $size);
            endforeach;
      endif;
 }

也试过这个:

function multi_thumbs_array(){
    global $post;
        $images = get_post_meta( $post->ID, 'images', true );
      if( $images ) {
        $size = 'thumbnail';
            foreach( $images as $image ) {
              $thumbs = wp_get_attachment_image_url($image, $size);
         }
     }
     if( is_array($thumbs) ){
        return implode(',', $thumbs);
    }

    return false;
 }

上面的代码可以正常工作,但它的列表 url 没有任何逗号。我尝试multi_thumbs_array()在 implode 中使用,但是当我这样做时它不起作用。谢谢!

标签: wordpress

解决方案


您需要稍微调整一下代码。Fe $thumbs 应该是一个数组,而不是一个字符串。

function multi_thumbs_array(){
    global $post;
    $thumbs=array();
    $images = get_post_meta( $post->ID, 'images', true );

    if( $images ) {
        $size = 'thumbnail';

        foreach( $images as $image ) {
            $thumbs[] = wp_get_attachment_image_url($image, $size);
        }
    } else {
        $get_first_image=get_attached_media( 'image', $post->ID );    
        $get_first_image=array_shift( array_values($get_first_image) );
        $thumbs_arr = wp_get_attachment_image_src( $get_first_image->ID );
        $thumbs[] = $thumbs_arr[0];
    }

    /* no need to check if $thumbs is array as it is 
       declared in array and it's type doesn't get modified in the code */

    return implode(',', $thumbs); //returns empty string if $thumbs is empty
}

推荐阅读