如何通过wordpress短代码处理多个图像ID?

时间:2016-05-02 11:23:21

标签: php wordpress-plugin

我试图通过wordpress短代码传递多个图像ID,目前我的wordpress短代码如下:

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

我的功能如下,想法是每个图像ID它会为每个图像ID返回一个html图像字符串,但目前它只生成一个:

// 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' );

我一直在寻找foreach循环,但我不知道如何返回多个值。

我的输出是1,它应该是5.

enter image description here

1 个答案:

答案 0 :(得分:1)

在逗号上拆分图像属性,不要直接从循环返回。

将生成的图像标记添加到字符串中,并在循环后返回字符串。

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' );