Нещодавно мені закортіло написати короткий код (shortcode) для вставляння програвача з переліком всіх долучених до публікації аудіофрагментів.
Тобто, я хочу до даної публікації доліпити кілька mp3 файлів, підписати їх і у публікації використати якийсь короткий код… Словом, нижче.
У файлі functions.php
дописуємо таке:
function get_player( $post ) {
$urls = array();
$titles = array();
$artists = array();
$attachments = get_children(
array('post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'audio/mpeg',
'order_by' => 'menu_order', 'order' => 'ASC'));
if( $attachments ) {
foreach ( $attachments as $att_id => $att ) {
// allow non-latin chars in file names:
$url = wp_get_attachment_url($att_id);
$url = preg_replace('#(.*/)([^/]*)$#e', "'\\1'.rawurlencode('\\2')", $url);
$url = rawurlencode( $url );
$urls[] = $url;
$title = rawurlencode( str_replace(",", ":", $att->post_title) );
$titles[] = $title;
}
$player_id = 'audioplayer-' . $post->ID;
$player = '<p class="audioplayer_container"><div class="np-audioplayer" id="'. $player_id .'">(No Adobe Flash Player?..)</div></p>' . "\n"
. '<script type="text/javascript">' . "\n"
. ' AudioPlayer.embed("' . $player_id . "\", {\n"
. ' soundFile: "' . implode(",", $urls) . "\" // ,\n"
. ' titles: "' . implode(",", $titles) . "\"\n"
. " });\n"
. "</script>\n";
return $player;
}
return false;
}
function playall( $atts ) {
global $post;
return get_player($post);
}
add_shortcode( "playall", "playall" ); |
function get_player( $post ) {
$urls = array();
$titles = array();
$artists = array();
$attachments = get_children(
array('post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'audio/mpeg',
'order_by' => 'menu_order', 'order' => 'ASC'));
if( $attachments ) {
foreach ( $attachments as $att_id => $att ) {
// allow non-latin chars in file names:
$url = wp_get_attachment_url($att_id);
$url = preg_replace('#(.*/)([^/]*)$#e', "'\\1'.rawurlencode('\\2')", $url);
$url = rawurlencode( $url );
$urls[] = $url;
$title = rawurlencode( str_replace(",", ":", $att->post_title) );
$titles[] = $title;
}
$player_id = 'audioplayer-' . $post->ID;
$player = '<p class="audioplayer_container"><div class="np-audioplayer" id="'. $player_id .'">(No Adobe Flash Player?..)</div></p>' . "\n"
. '<script type="text/javascript">' . "\n"
. ' AudioPlayer.embed("' . $player_id . "\", {\n"
. ' soundFile: "' . implode(",", $urls) . "\" // ,\n"
. ' titles: "' . implode(",", $titles) . "\"\n"
. " });\n"
. "</script>\n";
return $player;
}
return false;
}
function playall( $atts ) {
global $post;
return get_player($post);
}
add_shortcode( "playall", "playall" );
Після цього ми можемо у тілі повідомлення написати [playall]
. Ось тут — невеличка демонстрація.
Чому двічі rawurlencode
? Не знаю 🙂
До речі, у налаштуваннях вордпресівського Audio Player’а треба вимкнути «криптування» посилань.