我正在从头开始构建主题并使用Visual Composer插件。
我使用VC创建了一个自定义元素,允许用户上传一组图片。
当用户选择一组图像时,它们将作为图像ID数组返回。
我正在尝试创建一个将该ID数组转换为src
元素数组的短代码。
我知道我必须使用foreach
循环,但经过几个小时的在线查看,我似乎无法弄清楚如何正确编写它。显然只是在这里学习,所以要温柔;)
使自定义VC元素的代码看起来像这样(编辑下来):
vc_map(
array(
'base' => 'foo',
'params' => array(
array(
'type' => 'attach_images',
'param_name' => 'images',
),
);
);
);
我的短代码(到目前为止)看起来像这样:
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' );
我看过几个教程,我已经阅读了很多文章,我已经越走越远了,但还没有得到它的破解。我没有想到将所有失败的尝试添加到示例中有很多意义,因此我将上面的代码仅删除了我认为合适的行。
任何帮助理解如何将它们放在一起的方法一如既往地非常感谢。
谢谢!
答案 0 :(得分:1)
您可以在循环中使用 wp_get_attachment_image_src 函数来获取src元素。
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' );
有关函数 wp_get_attachment_image_src()的更多信息:https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/