Show audio player only in specific post type category

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;

}

Topic woocommerce-offtopic audio categories Wordpress

Category Web


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;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.