用于从媒体库ID输出多个图像URL的快捷代码

时间:2019-03-12 作者:Jalapeno Jack

我正在编写一些自定义快捷码,它从其ID输出一个图像url。我希望快捷码的用法如下:

[imagez id=“211046,211034”]

这是我的代码:

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

       return wp_get_attachment_url($id);

 }
add_shortcode(\'imagez\', \'image_thingy\');
有了这个,我只能检索第一个ID的url,而不能像上面的示例那样检索多个逗号分隔的url。我怎样才能做到这一点?谢谢

1 个回复
最合适的回答,由SO网友:Qaisar Feroz 整理而成

试试这个

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\');
以下代码将URL包装在<img> 标签:

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

相关推荐

Shortcode is not working

通过阅读教程,我创建了一个简单的快捷代码:<?php /* Plugin Name: GT NoTranslate Shortcode Description: Shortcode to wrap a span with the \"notranslate\" span around text. Version: 0.1 BETA Author: Andrew Truckle Author URI: http://www.trucklesoft.co.