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!

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');
7
  • 1
    Thanks for the reply. I get a syntax error, unexpected ';' on the line $output .= wp_get_attachment_url($id). ', '; – Jalapeno Jack Mar 12 '19 at 16:29
  • Improved and updated my answer. please check it now. – Qaisar Feroz Mar 12 '19 at 16:53
  • Let me know if it works. – Qaisar Feroz Mar 12 '19 at 17:01
  • 1
    Thanks this worked perfectly. If you have the time, could you show me how to wrap each outputted url in an image tag? – Jalapeno Jack Mar 12 '19 at 17:10
  • 1
    Perfect, That's great! Once again, only if you have time, could you please add some comments to the code to explain what is happening, I would like to learn more. Thanks again! – Jalapeno Jack Mar 12 '19 at 17:27

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.