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?
3 Answers
Plugin option
When searching for a plugin, it is important to check:
- Compatible up to, supports current WordPress version?
- Last updated, too long ago?
- Support, too many bug reports? Level of support in the forum or in the official plugin page.
- Compatibility, if the plugin hasn’t been updated for a while or is not compatible with the current WP version, check the previous WordPress versions. Sometimes the plugin is not updated because it simply works.
Do it yourself
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>';
}
}
Related Q&A
- How to add audio files to wordpress blog and making it auto play?
Useful info
- Creating a WordPress shortcode
- Where to put my code: plugin or functions.php?
- Create a Functionality Plugin Instead of Using Functions.php