Search code examples
phparrayswordpressforeachvisual-composer

Wordpress; Convert array of image ids to urls


I'm building a theme from scratch and am utilizing the Visual Composer plugin.

I've made a custom element using VC to allow a user to upload a set of images.

When a users selects a set of images, they get returned as an array of image ids.

I'm trying to create a shortcode that will convert that array of ids to an array of src elements.

I know I have to use a foreach loop, but after hours of looking online I can't seem to figure out how to write it correctly. Obviously just learning here, so be gentle ;)

My code that makes the custom VC element looks like this (edited down):

vc_map( 
    array(
        'base' => 'foo',
        'params' => array( 
            array(
                'type' => 'attach_images',
                'param_name' => 'images',
            ),
        );
    );
);

My shortcode (so far) looks like this:

function foo_shortcode($atts){

    extract( shortcode_atts( array (
        'images' => '',
    ), $atts ) );

    $images = $unkonwn_foreach_loop;

    $output = '<div class="gallery">' . $missing_list_of_src_elements . '</div>' . "\n";

    return $output;

}
add_shortcode( 'foo', 'foo_shortcode' );

I've looked at several tutorials, I've read a bunch of articles, I've gotten closer and further away, but haven't got it cracked yet. I didn't think there was much point in adding all my failed attempts as examples, so I stripped down the code above to only the lines that I know are fine.

Any help understanding how to put this together is, as always, greatly appreciated.

thanks!


Solution

  • You can use the function wp_get_attachment_image_src inside your loop to get the src elements.

    function foo_shortcode($atts){
    
            extract( shortcode_atts( array (
                'images' => '',
            ), $atts ) );
    
            $output = '<div class="gallery">';
    
            // temp debug for check if $images is array
            //var_dump($images);
    
            // string to array
            $array_images_ids = explode(',', $images);
    
            foreach($array_images_ids as $id){
                $img = wp_get_attachment_image_src($id, 'thumbnail');
                $output .= '<img src="' . esc_url($img[0]) . '" />';
            }
    
            $output .= '</div>' . "\n";
    
            return $output;
    
        }
        add_shortcode( 'foo', 'foo_shortcode' );
    

    For more info about the function wp_get_attachment_image_src() : https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/