skip to Main Content

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


  1. Chosen as BEST ANSWER

    I got the result I wanted. Here is the solutions.

    Add this to the functions.php:

    <?php add_filter( 'the_excerpt', 'shortcode_unautop');
    add_filter( 'the_excerpt', 'do_shortcode'); ?>
    

    Then, inside the loop add:

    <?php echo do_shortcode("[audio]"); ?>
    

    All together it look like this:

        <?php
    
    if ( have_posts() ) :
        while ( have_posts() ) : the_post(); ?>
    
        <?php the_post_thumbnail(); ?>
    
        <?php the_title() ?>
    
                <?php the_excerpt() ?>
    
    <?php echo do_shortcode("[audio]"); ?>
            
        <?php endwhile; ?>
    

  2. Your comment:

    The excerpt is all the text up to and including the audio tag.

    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 substrs third parameter by an amount that equals the length of the string [/audio]:

    $closing_audio_tag = '[/audio]';
    
    // The excerpt is all the text up to and including the audio tag.
    $excerpt = substr(
        $content,
        0,
        strpos($content, $closing_audio_tag) + strlen($closing_audio_tag)
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search