I have a blog which I sometimes use for audio clips. I want to put an Audio Player on the frontpage of my blog.
How can I put the player after the title or make its code part of post excerpts?
I have a blog which I sometimes use for audio clips. I want to put an Audio Player on the frontpage of my blog.
How can I put the player after the title or make its code part of post excerpts?
When searching for a plugin, it is important to check:
You are in control of what happens and when it happens.
Here I’m creating a function that will print a Html5 Audio Tag based on two audio files uploaded to any post or page -one mp3
and one ogg
.
Reference tutorials: [one] and [two]
In the theme template files (single.php
, page.php
, etc), put the function print_audio_attachments_as_html5
like this:
<header class="entry-header">
<h1 class="entry-title"><?php the_title(); ?></h1>
</header>
<?php print_audio_attachments_as_html5( $post->ID ); ?>
<div class="entry-content">
<?php the_content(); ?>
Note that the function is placed inside The Loop, so $post->ID
is available.
Put the following function at the end of your theme functions file
/wp-content/themes/your-theme/functions.php
check the comments in the code
function print_audio_attachments_as_html5( $post_id )
{
// Parameters for our search
$args_mp3 = array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'numberposts' => 1, // only one file
'post_mime_type' => 'audio/mpeg', // Mp3 audio mime type
);
$args_ogg = array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'numberposts' => 1,
'post_mime_type' => 'audio/ogg', // Firefox does not supports Mp3
);
// Get audio files
$mp3 = get_children( $args_mp3 );
$ogg = get_children( $args_ogg );
// If there's any result in one of the get_children, execute code
if( $mp3 || $ogg )
{
// Start Audio tag
echo '<audio loop="loop" autoplay="autoplay" controls="controls">';
// Mp3 source
if( $mp3 ) {
$id = array_pop( array_keys( $mp3 ) );
$mp3_url = wp_get_attachment_url( $id );
echo '<source src="' . $mp3_url . '" />';
}
// Ogg source
if( $ogg ) {
$id = array_pop( array_keys( $ogg ) );
$ogg_url = wp_get_attachment_url( $id );
echo '<source src="' . $ogg_url . '" />';
}
// Close Audio tag
echo '</audio>';
}
}