0

I have a code that autoplays audio and it is working well but the stuff is I want the autoplay to only run in a specified woocommerce category. Any help will be appreciated. The code is below.

add_filter( 'woocommerce_short_description', 'wpse_67108_autplay_music' );

function wpse_67108_autplay_music( $content )
{
if ( ! is_singular( 'product' ) )
{
    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
    $autoplay = in_category( 'premium' ) ? 'autoplay' : '';
    $audio = "<audio src='$url' controls controlsList = 'nodownload' $autoplay loop></audio>";
}

return $audio . $content;

}

0

Have you tried has_category? You can add a check to make sure the post has the specified category. If not then return the content un changed like below:

<?php

add_filter( 'woocommerce_short_description', 'wpse_67108_autplay_music' );

function wpse_67108_autplay_music( $content ) {
    if ( ! is_singular( 'product' ) && ! has_category( '<your specific category here>' )) { 
        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
        $autoplay = in_category( 'premium' ) ? 'autoplay' : '';
        $audio = "<audio src='$url' controls controlsList = 'nodownload' $autoplay loop></audio>";
    }

    return $audio . $content;
}

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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