I’m trying to display the audio player in the post excerpt in WordPress. On this website I found the following code that I added to functions.php:
/**
* Create an excerpt that includes the audio for podcasts.
* @return string The excerpt HTML
*/
function wp_podcast_excerpt() {
// Gets the post content
$content = get_the_content();
// Find the position of the audio shortcode in the content
$audiopos = strpos($content,'[audio');
if($audiopos) {
// The excerpt is all the text up to and including the audio tag.
$excerpt = substr($content, 0, strpos($content,'[/audio]'));
// Apply wordpress filters.
$excerpt = apply_filters('the_content', $excerpt);
// Strip out images.
$excerpt = preg_replace("/<img[^>]+>/i", "", $excerpt);
echo $excerpt;
} else {
the_excerpt();
}
}
In the loop I have included:
<?php wp_podcast_excerpt(); ?>
This only shows the text and nothing else. What am I doing wrong?
2
Answers
I got the result I wanted. Here is the solutions.
Add this to the functions.php:
Then, inside the loop add:
All together it look like this:
Your comment:
Is incorrect. At that point in time,
$excerpt
contains the text up to, but excluding the closing audio tag. I’d imagine you’d like to have this included in$excerpt
, so that it is properly parsed by WordPress filters.You could do all manor of things to ensure that it’s included when applying filters. One very straight-forward way would be to increase
substr
s third parameter by an amount that equals the length of the string[/audio]
: