MrJoshFisher
MrJoshFisher

Reputation: 1123

How can I process multiple image ids through a wordpress shortcode?

Im trying to pass multiple image ids through a wordpress shortcode, currently my wordpress shortcode is as follows:

[lemonslider images="35,46,43,42,41"]

And my function for this as follows, the idea was for each image id it would return a html image string for each of the image ids, but currently it only generates one:

// LEMON SLIDER SHORTCODE

function lemon_slider( $atts ){
$a = shortcode_atts( array(
    'images' => '44',
    'toshow' => '5',
), $atts );

$SlImages = $a['images'];
$arrlength = count($SlImages);

for($x = 0; $x < $arrlength; $x++) {
    $image_attributes = wp_get_attachment_image_src( $attachment_id = $SlImages);
    return ('<img src=' . $image_attributes[0] . ' width=' . $image_attributes[1] . ' height=' . $image_attributes[2] . ' />');

}

}
add_shortcode( 'lemonslider', 'lemon_slider' );

Ive been looking at foreach loops but Im not sure how to return multiple values.

my output is 1 and it supposed to 5.

enter image description here

Upvotes: 1

Views: 448

Answers (1)

beerwin
beerwin

Reputation: 10327

Split your images attribute on the comma, and don't return directly from the loop.

Add your generated image tags to a string and return the string after the loop.

function lemon_slider( $atts ){
    $a = shortcode_atts( array(
        'images' => '44',
        'toshow' => '5',
    ), $atts );

    $SlImages = $a['images'];
    $arrlength = count($SlImages);

    // split images parameter on the comma
    $SlImages = explode(",", $a['images']);

    // define an empty string for the initial return value
    $ret = "";

    foreach ($SlImages as $image) {
         $image_attributes = wp_get_attachment_image_src( $attachment_id = $image);
         // add each image tag to the return string
         $ret .= ('<img src=' . $image_attributes[0] . ' width=' . $image_attributes[1] . ' height=' . $image_attributes[2] . ' />');
    }

    // return the result
    return $ret;
}
add_shortcode( 'lemonslider', 'lemon_slider' );

Upvotes: 1

Related Questions