我有一个自动播放音频的代码,它工作得很好,但问题是我希望自动播放只能在指定的woocommerce类别中运行。任何帮助都将不胜感激。代码如下所示。
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;
}
SO网友:mikerojas
你试过了吗has_category
? 您可以添加检查以确保帖子具有指定的类别。如果没有,则返回未更改的内容,如下所示:
<?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;
}