Search code examples
wordpresscallbackadvanced-custom-fieldswordpress-gutenberggutenberg-blocks

How to implement JS callback for acf_register_block()


I'm currently in the process of updating a website so that it supports Wordpress Blocks (5.0+) via Advanced Custom Fields. I have a block which needs some JS and was wondering if there is a way to implement a JS callback either via acf_register_block() or register_block_type() so that a JS function is called when the block is added to a page in the CMS?


Solution

  • For anyone else looking, the easiest way so far would be to call the existing JS function for your block from within the block render template itself, however it should only call the function if the admin page is showing (so that it doesn't show inline scripts on the front end).

    eg.

    function slider_block_html(){
      //html output here
    
      if(is_admin()){
        echo "<script>sliderInit();</script>";
      };
    }