【发布时间】:2017-08-02 21:50:41
【问题描述】:
谁能帮助我使用 foreach 循环创建一个短代码,如下所示?
这个短代码的目的是生成一个播放列表,并使用开始和结束标签:
[zoomsounds id="favorites_playlist"] [/zoomsounds]
在这些标签之间,每首要添加到播放列表的歌曲都有自己的短代码,如下所示:
[zoomsounds_player config="favorites-playlist" source="'.$source.'" type="detect" songname="'.$title.'" init_player="off" play_target="footer"]
假设用户的播放列表中有 2 首歌曲,整个短代码如下所示:
[zoomsounds id="favorites_playlist"][zoomsounds_player config="favorites-playlist" source="http://www.test.com/sound/brobob.mp3" type="detect" songname="Song 1" init_player="off" play_target="footer"][zoomsounds_player config="favorites-playlist" source="http://www.test.com/sound/brobob2.mp3" type="detect" songname="Song 2" init_player="off" play_target="footer"][/zoomsounds]
如您所见,每首歌曲的短代码一个接一个,包含在开始/结束标签中。
我认为可以做到这一点的最简单方法是使用 foreach 循环来生成每首歌曲的短代码。这是我写的简单函数。
function streamFavoritesPlaylist() {
$favs[] = get_user_favorites();
echo do_shortcode('[zoomsounds id="favorites_playlist"]');
foreach ($favs[0] as $fav) {
$title = get_the_title($fav);
$post = get_post($fav);
$post_slug = $post->post_name;
$source = '.../mp3/'.$post_slug.'.mp3';
$song_name = get_the_title($fav);
echo do_shortcode('[zoomsounds_player config="favorites-playlist" source="'.$source.'" type="detect" songname="'.$title.'" init_player="off" play_target="footer"]');
}
echo do_shortcode('[/zoomsounds]');
}
显然,这样做是错误的。更不用说,结束标签没有被占用,而是以文本形式显示。也许这就是为什么整个事情都不起作用的原因?
我应该提到,通过使用整个简码它自己可以正常工作。只有当我尝试以这种方式构建短代码时它才不起作用。
你会建议我如何完成这样的事情?非常感谢。
更新: 感谢大家的意见。这是我想出的,与@DACrosby 发布的和@TheManiac 建议的类似。
function streamFavoritesPlaylist() {
$favs[] = get_user_favorites();
$shortcode_full = "";
foreach ($favs[0] as $fav) {
$title = get_the_title($fav);
$post = get_post($fav);
$post_slug = $post->post_name;
$source = '.../mp3/'.$post_slug.'.mp3';
$song_name = get_the_title($fav);
$shortcode = '[zoomsounds_player config="favorites-playlist" source="'.$source.'" type="detect" songname="'.$title.'" init_player="off" play_target="footer"]';
$shortcode_full .= $shortcode;
}
return '[zoomsounds id="favorites_playlist"]'.$shortcode_full.'[/zoomsounds]';
}
而我实际上需要生成的短代码,我正在使用:
<?php echo do_shortcode(streamFavoritesPlaylist()); ?>
它运行良好。再次感谢社区。p>
【问题讨论】:
-
我可能没有关注,但如果您只是想生成简码文本,我认为您不应该使用
do_shortcode。将整个代码生成为单个字符串,然后在结果上调用do_shortcode。 -
@TheManiac 这很有意义。让我试试看。你有机会给我一个快速的sn-p吗?不管怎样,谢谢!
-
看起来 DACrosby 已经为你做了一个 sn-p。很确定他是对的。
-
@TheManiac 是的,我在你的建议后想出了什么。非常感谢。
标签: php wordpress loops foreach shortcode