0

I have a code that automatically auto-plays audio, I found it on this site and it works. The issue there is that it auto-plays it site-wide. Is there a way to only enable the autoplay for specific post types? The code is below.

add_filter( 'the_content', 'wpse_67108_autplay_music' );

function wpse_67108_autplay_music( $content )
{
    if ( ! is_singular() )
    {
        return $content;
    }

    $audio_files = get_children(
        array (
            'post_parent'    => get_the_ID(),
            'post_status'    => 'inherit',
            'post_type'      => 'attachment',
            'post_mime_type' => 'audio'
        )
    );

    $audio = '';

    if ( $audio_files )
    {
        $id   = array_pop( array_keys( $audio_files ) );
        $url  = wp_get_attachment_url( $id );
        // add a 'controls' attribute to enable controls
        $audio = "<audio src='$url' controls autoplay loop></audio>";
    }

    return $audio . $content;
}

1 Answer 1

0

This is untested, but it seems to me that you could simply replace the:

$audio = "<audio src='$url' controls autoplay loop></audio>";

with

$autoplay = is_singular( 'your_post_type' ) ? 'autoplay' : '';
$audio = "<audio src='$url' controls $autoplay loop></audio>";

I.e. We use the $autoplay variable to store the autoplay attribute, and if the current page is the single page for your post type (your_post_type), then we set the variable value to autoplay.

But if you want to add/enable the audio player only on your custom post type pages, then you just need to change the is_singular() in your code to is_singular( 'your_post_type' ). Something like:

function wpse_67108_autplay_music( $content )
{
    if ( ! is_singular( 'your_post_type' ) )
    {
        return $content;
    }

    // ... the rest of your code here.
}
4
  • 1
    This worked for me. Thanks a million Commented Feb 4, 2021 at 13:14
  • Glad it worked for you! And would you mind marking my answer as "correct"? ( just tick the check-mark next to my answer :) )
    – Sally CJ
    Commented Feb 4, 2021 at 15:13
  • Hello, please I just ran into another error. I need the player to be totally removed except on the post type I specify. It currently doesn't auto play on any other post type except the one specified but I want it totally removed except on specified post types Commented Feb 18, 2021 at 4:47
  • As said in my answer, use the original wpse_67108_autplay_music() code in the question, but change the only is_singular() there to is_singular( 'your_post_type' ). Note though, if you have a new requirement, please post a separate question for that. :)
    – Sally CJ
    Commented Feb 18, 2021 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.