Revolutionize Your WordPress Blog with a Custom Audio Player and Reading Time Display
In today’s fast-paced digital world, providing diverse ways for users to consume content is crucial. We’ve developed a solution that not only enhances the reading experience but also offers an audio alternative for your WordPress posts. Our custom-built feature seamlessly integrates a reading time indicator and an audio player into your blog posts, improving accessibility and user engagement.
This article will guide you through our innovative solution, which places the estimated reading time on the left side of your post and a customizable audio player on the right. This dual approach caters to different user preferences, allowing readers to either skim through the content or listen to it on the go.
The Challenge
- Meeting the growing demand for audio content in text-based blogs
- Overcoming limitations of standard WordPress audio players
- Addressing accessibility concerns for visually impaired users
- Integrating audio seamlessly with existing blog posts
- Providing users with clear information about content length
Our Solution
We’ve developed a comprehensive solution that enhances your WordPress posts with two key features:
- Left-aligned Reading Time: An accurate estimation of how long it takes to read the article, displayed prominently at the beginning of the post.
- Right-aligned Custom Audio Player: A sleek, user-friendly audio player that allows visitors to listen to the content instead of reading it.
This solution integrates PHP, JavaScript, and CSS to create a seamless user experience that caters to both readers and listeners.
Key Features
- Accurate reading time calculation and left-aligned display
- Right-aligned, customizable audio player with intuitive controls
- “Play to Listen” button for easy audio access
- Seek functionality for precise navigation within the audio
- Play/Pause control for user convenience
- Current time and total duration display
- Responsive design ensuring compatibility across devices
How It Works
- Reading time is calculated based on the post content
- Audio files are added to WordPress posts via custom fields
- PHP function generates HTML for reading time and audio player
- Custom HTML is injected into the post content
- JavaScript manages user interactions and audio playback
- CSS styles ensure proper left and right alignment and overall design
Benefits
- Enhanced accessibility for all users, including those with visual impairments
- Increased user engagement through multi-modal content presentation
- Flexibility in content consumption (read or listen)
- Clear expectations set for readers with visible reading time
- Potential SEO advantages from increased time on page and reduced bounce rates
- Professional and polished appearance of blog posts
Implementation
Our solution utilizes:
- PHP for server-side logic, reading time calculation, and WordPress integration
- JavaScript for interactive audio controls and dynamic content updates
- CSS for styling, responsiveness, and left/right alignments
- WordPress hooks and functions for seamless integration with your existing theme
This PHP Code Does the Following:
- Calculates the estimated reading time based on word count
- Retrieves the audio URL from post meta data
- Generates HTML for the left-aligned reading time display
- Creates HTML for the right-aligned audio player and controls
- Injects the generated HTML into the post content
To Use This Code:
- Add the PHP function to your theme’s functions.php file
- Enqueue necessary JavaScript and CSS files
- Add audio files to your posts using a custom field (e.g., ‘audio_url’)
- Ensure your theme’s CSS accommodates the new left and right aligned elements
WordPress Post Audio Link Insertion for Function.php
To add the PHP function coding to your theme’s functions.php:
//WordPress Post Audio Link Insertion
function add_audio_url_meta_box() {
add_meta_box(
'audio_url_meta_box',
'Audio URL',
'audio_url_meta_box_callback',
'post',
'side',
'default'
);
}
add_action('add_meta_boxes', 'add_audio_url_meta_box');
function audio_url_meta_box_callback($post) {
wp_nonce_field('audio_url_meta_box', 'audio_url_meta_box_nonce');
$value = get_post_meta($post->ID, '_audio_url', true);
echo '<label for="audio_url_field">Audio URL:</label>';
echo '<input type="text" id="audio_url_field" name="audio_url_field" value="' . esc_attr($value) . '" size="25" />';
}
function save_audio_url_meta_box_data($post_id) {
if (!isset($_POST['audio_url_meta_box_nonce']) || !wp_verify_nonce($_POST['audio_url_meta_box_nonce'], 'audio_url_meta_box')) {
return;
}
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if (isset($_POST['audio_url_field'])) {
update_post_meta($post_id, '_audio_url', sanitize_text_field($_POST['audio_url_field']));
}
}
add_action('save_post', 'save_audio_url_meta_box_data');
Reading Time and Audio Player for Function.php
To add the PHP function coding to your theme’s functions.php:
function add_reading_time_and_audio($content) {
if (is_single() && in_the_loop() && is_main_query()) {
$word_count = str_word_count(strip_tags($content));
$reading_time = ceil($word_count / 200);
$post_id = get_the_ID();
$audio_url = get_post_meta($post_id, '_audio_url', true);
$icon = '<span class="reading-time-icon"><i class="fas fa-book-reader" aria-hidden="true"></i></span>';
$reading_time_html = '<span class="reading-time">' . $reading_time . ' min read</span>';
$audio_html = '';
if ($audio_url) {
$audio_html = '
<div class="audio-container">
<div class="reading-time-and-button">
<div class="reading-time-wrapper">' . $icon . $reading_time_html . '</div>
<button class="play-to-listen-btn" data-player="audio-player-' . $post_id . '" aria-label="Play audio">
<span class="dashicons dashicons-controls-play" aria-hidden="true"></span> Play to Listen
</button>
</div>
<div class="audio-player-wrapper" style="display: none;">
<audio id="audio-player-' . $post_id . '" class="custom-audio-player">
<source src="' . esc_url($audio_url) . '" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<button class="play-pause-btn" data-player="audio-player-' . $post_id . '" aria-label="Play/Pause">
<span class="dashicons dashicons-controls-pause" aria-hidden="true"></span>Pause
</button>
<span class="current-time" aria-label="Current time">0:00</span>
<input type="range" class="seek-slider" min="0" max="100" value="0" step="0.1" aria-label="Seek audio">
<span class="duration" aria-label="Total duration" style="display: none;">0:00</span>
</div>
</div>';
}
$content = $audio_html . $content;
}
return $content;
}
add_filter('the_content', 'add_reading_time_and_audio');
// You might need this if dashicons are not already enqueued
function enqueue_dashicons() {
wp_enqueue_style('dashicons');
}
add_action('wp_enqueue_scripts', 'enqueue_dashicons');
Reading Time Calculation Script
To add the Script PHP coding to your website:
// Function to calculate reading time
function calculateReadingTime() {
const text = document.body.innerText;
const wordCount = text.trim().split(/\s+/).length;
const readingTime = Math.ceil(wordCount / 200); // Assuming 200 words per minute
document.querySelector('.reading-time').textContent = `${readingTime} min read`;
}
// Call the function when the page loads
window.onload = calculateReadingTime;
Audio Player Script
To add the Script PHP coding to your website:
jQuery(document).ready(function($) {
$('.play-to-listen-btn').on('click', function() {
var $this = $(this);
var playerId = $this.data('player');
var player = document.getElementById(playerId);
var playerWrapper = $('#' + playerId).parent('.audio-player-wrapper');
var playPauseBtn = playerWrapper.find('.play-pause-btn');
var durationDisplay = playerWrapper.find('.duration');
// Start fade-out animation
$this.addClass('fading-out');
// After animation completes, hide the button
setTimeout(function() {
$this.addClass('hidden');
}, 500); // 500ms matches the animation duration
playerWrapper.slideDown();
player.play();
updatePlayPauseButton(playPauseBtn, false);
// Hide duration initially
durationDisplay.hide();
});
$('.custom-audio-player').each(function() {
var player = this;
var playPauseBtn = $(this).siblings('.play-pause-btn');
var seekSlider = $(this).siblings('.seek-slider');
var currentTime = $(this).siblings('.current-time');
var durationDisplay = $(this).siblings('.duration');
function formatTime(seconds) {
var minutes = Math.floor(seconds / 60);
var remainingSeconds = Math.floor(seconds % 60);
return minutes + ":" + (remainingSeconds < 10 ? "0" : "") + remainingSeconds;
}
function updatePlayPauseButton(button, isPaused) {
if (isPaused) {
button.html('<span class="dashicons dashicons-controls-play"></span>Play');
} else {
button.html('<span class="dashicons dashicons-controls-pause"></span>Pause');
}
}
function updateSlider() {
var percentage = (player.currentTime / player.duration) * 100;
seekSlider.val(percentage);
seekSlider.css('background', `linear-gradient(to right, #4CAF50 0%, #4CAF50 ${percentage}%, #ddd ${percentage}%, #ddd 100%)`);
}
function setSliderMax() {
seekSlider.attr('max', 100);
durationDisplay.text(formatTime(player.duration));
}
player.addEventListener('loadedmetadata', function() {
setSliderMax();
});
player.addEventListener('canplay', function() {
setSliderMax();
});
player.addEventListener('timeupdate', function() {
updateSlider();
currentTime.text(formatTime(player.currentTime));
});
playPauseBtn.on('click', function() {
if (player.paused) {
player.play();
updatePlayPauseButton($(this), false);
} else {
player.pause();
updatePlayPauseButton($(this), true);
}
});
seekSlider.on('input', function() {
var time = ($(this).val() / 100) * player.duration;
player.currentTime = time;
updateSlider();
// Show duration when user starts dragging
durationDisplay.show();
});
player.addEventListener('ended', function() {
updatePlayPauseButton(playPauseBtn, true);
seekSlider.val(0);
updateSlider();
});
// Ensure the duration is set correctly
$(player).on('loadedmetadata', function() {
setSliderMax();
});
});
});
Reading Time & Audio Player CSS
To add the CSS coding to your website:
.audio-container {
margin-bottom: 20px;
}
.reading-time-and-button {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
flex-wrap: wrap;
}
.reading-time-wrapper {
font-size: 14px;
color: #666;
display: flex;
align-items: center;
}
.reading-time-icon {
margin-right: 4px;
}
.reading-time {
margin-right: 10px;
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
.play-to-listen-btn.fading-out {
animation: fadeOut 0.5s ease-out forwards;
pointer-events: none;
}
.play-to-listen-btn.hidden {
display: none;
}
.play-to-listen {
margin-left: auto;
}
.play-to-listen-btn, .play-pause-btn {
background-color: #f0f0f0;
border: 1px solid #ccc;
border-radius: 4px;
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
color: #333;
font-size: 14px;
padding: 5px 10px;
width: 150px;
transition: background-color 0.3s ease;
}
.play-to-listen-btn:hover, .play-pause-btn:hover {
background-color: #e0e0e0;
}
.play-to-listen-btn .dashicons, .play-pause-btn .dashicons {
margin-right: 5px;
font-size: 18px;
}
.audio-player-wrapper {
width: 100%;
margin-top: 10px;
display: flex;
align-items: center;
}
.custom-audio-player {
display: none;
}
.current-time, .duration {
font-size: 12px;
margin: 0 10px;
min-width: 45px;
text-align: center;
}
.seek-slider {
flex-grow: 1;
-webkit-appearance: none;
width: 100%;
height: 10px;
border-radius: 5px;
background: #ddd;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
}
.seek-slider:hover {
opacity: 1;
}
.seek-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
border-radius: 50%;
background: #0073aa;
cursor: pointer;
box-shadow: 0 0 0 3px #fff, 0 0 0 6px rgba(0, 115, 170, 0.3);
}
.seek-slider::-moz-range-thumb {
width: 20px;
height: 20px;
border-radius: 50%;
background: #0073aa;
cursor: pointer;
box-shadow: 0 0 0 3px #fff, 0 0 0 6px rgba(0, 115, 170, 0.3);
}
.seek-slider:focus::-webkit-slider-thumb {
box-shadow: 0 0 0 3px #fff, 0 0 0 6px rgba(0, 115, 170, 0.5);
}
.seek-slider:focus::-moz-range-thumb {
box-shadow: 0 0 0 3px #fff, 0 0 0 6px rgba(0, 115, 170, 0.5);
}
Some Additional Notes:
- This solution is compatible with most WordPress themes
- Performance impact is minimal, but caching is recommended for high-traffic sites
- Future enhancements could include playback speed control and playlist functionality
- Regular testing and updates are advised to maintain compatibility with WordPress core updates
Conclusion
By implementing this custom solution, you’re not just adding an audio player to your WordPress posts; you’re creating a more inclusive, user-friendly blogging experience. The left-aligned reading time and right-aligned audio player work in tandem to give your readers options and valuable information upfront. This enhancement can lead to increased engagement, improved accessibility, and a modern feel to your blog.
We encourage you to implement this solution and customize it to fit your specific needs. As always, we welcome feedback and suggestions for further improvements. Happy blogging!