permalinks - shortcode to output multiple images urls from media library id

admin2025-06-02  2

I am writing some custom shortcode which outputs an images url from its ID. I would like the shortcode usage to be as follows:

[imagez id="211046, 211034"]

This is my code:

function image_thingy($atts) {
    extract(shortcode_atts(array(
        'id' => 1,
     ), $atts));

       return wp_get_attachment_url($id);

 }
add_shortcode('imagez', 'image_thingy');

With this I can only retrieve the url of the first ID only, and not multiple comma separated like in the above example. How could I achieve this? Thanks!

I am writing some custom shortcode which outputs an images url from its ID. I would like the shortcode usage to be as follows:

[imagez id="211046, 211034"]

This is my code:

function image_thingy($atts) {
    extract(shortcode_atts(array(
        'id' => 1,
     ), $atts));

       return wp_get_attachment_url($id);

 }
add_shortcode('imagez', 'image_thingy');

With this I can only retrieve the url of the first ID only, and not multiple comma separated like in the above example. How could I achieve this? Thanks!

Share Improve this question edited Mar 12, 2019 at 16:53 Jalapeno Jack asked Mar 12, 2019 at 16:05 Jalapeno JackJalapeno Jack 1697 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

Try this

function image_thingy($atts) {
    // Merge attribtes from shortcode with defaults
    extract(shortcode_atts(array(
        'id' => 1,
        ), $atts));

    // Extract id's from shortcode attributes and convert into an array
    $ids = explode(',',$atts['id']);

    $output = ''; // Variable that holds the shortcode output, at the end this will be returned

    // Loop through ids and fetch urls, and add a comma with a blank space
    foreach($ids as $id){
       $output .= wp_get_attachment_url($id). ', ';
    }
    // remove comma and blank space from the end of $output, and finally return $output
    return rtrim($output,', ');
}
add_shortcode('imagez', 'image_thingy');

The following code wraps the urls in <img> tags:

function image_thingy($atts) {
    extract(shortcode_atts(array(
        'id' => 1,
        ), $atts));
    $ids = explode(',',$atts['id']);
    $output = '';
    foreach($ids as $id){
       $output .= '<img src="'. wp_get_attachment_url($id) . '"/> ';
    }
    return $output;
}
add_shortcode('imagez', 'image_thingy');
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748814069a313942.html

最新回复(0)