How to check if a WordPress core block is active in sidebar

I have a widget area and I want to enqueue a stylesheet only if a core block is active in it. I tried the following code:

// if has audio block.
if (has_block('audio')) {
    wp_enqueue_style('audio-css', get_template_directory_uri() . '/assets/css/audio.css');
}

And it kinda worked. The problem is it only works if the audio block is added in a post. But I want to check if the audio block is added to widget areas like the sidebar. And not just on a post but also on the front page if the block is active in the sidebar.

I even tried the following code, but it didn't work.

if (is_home()) {
    if (has_block('audio')) {
        wp_enqueue_style('audio-css', get_template_directory_uri() . '/assets/css/audio.css');
    }
}

I'm hoping someone can help me solve this or point me in the right direction to solving this.

Thanks :)

Topic block-editor wp-enqueue-style widgets css theme-development Wordpress

Category Web

About

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