1

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 :)

5
  • developer.wordpress.org/reference/functions/is_active_widget you need a few more parameters
    – rudtek
    CommentedFeb 27, 2022 at 15:12
  • Are you referring to a widget or a block? There is an audio block, and there is an audio shortcode, but there is no audio widget. Can you update your question to be more specific? Use the edit link under the tags and be very specific and careful about the wording and terminology, add screenshots if you can
    – Tom J Nowell
    CommentedFeb 27, 2022 at 15:46
  • As a simpler workaround, you could include your script into your main script file but ONLY execute if one of the elements you want to effect is present by checking for the length. if( $( '#audio-widget-or-block-element' ).length > 0 ) { //run your script }CommentedFeb 27, 2022 at 16:48
  • Hi, @TomJNowell I have edited my question. I am actually referring to a block and not a widget. Sorry for the confusion
    – Zeddy Emy
    CommentedFeb 27, 2022 at 19:42
  • Thanks for clarifying. Note that while it may still be useful to know the answer to this question, there is a super-easy solution to your original problem of how to enqueue CSS only when the block is used that does not require you to know if the block is used. Make sure in future to ask how to solve your problem, not how to implement your solution.
    – Tom J Nowell
    CommentedFeb 27, 2022 at 20:58

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.