Allow Custom JS in Block

Similar to how we have the Expresions option in the block attributes, I want to be able to write custom JS (primarily to write if statements) in the Expressions block using the attribute IDs. I can think of many uses for this, but my immediate need is to create a <style></style> code block which I want to be able to populate dynamically based on the attributes chosen. I’m trying to avoid a huge CSS library that covers every possible media query and class (like BS or TW) and only inject the styles as needed on each page. But there have been other times I wish I had more control over the output. -Thanks!

@jonroc there are a couple of things that make this a bit complicated:

  • You would have to write React code for constructing virtual DOM
  • Such blocks could not be Hybrid blocks because JS is not executed on the backend

If you mainly need to write IF statements the Block Condition action might be a better fit.

Ok, I see the issue here. The Block Conditions are not advanced enough for what I need.

One thing I’ve been doing is creating 99% of the block in PG and then moving the code that is generated for WP into a PG blocks folder. This exports the block code to the theme, but since I no longer need the initial setup for the block, I disable that block in PG, and the only thing I have to do is adjust the block’s code in a text editor to what I need and manually enqueue the block. The problem I have is that the inc/custom.php is called before the blocks, so I don’t have access to the PG helper files that are needed to run the block properly.

Is there no way to put the inc/custom.php at the bottom of function.php so I can have these custom blocks work quickly and easily? In the meantime, I can add the enqueued files manually at the bottom of functions.php, but that’s dangerous because we have no control over functions.php, and it’s easy for a team member to accidentally overwrite this.

-Thanks!

@jonroc the best way is to use WP hooks to ensure that the code runs at the correct time. For example, blocks are registered in the init hook with the default priority 10.

If you wish to run some code after all the blocks are registered use this in inc/custom.php:

add_action( 'init',function() {
    //do something
}, 100);

The priority parameter 100 causes this hook to be called at the end.

(posting the same to the linked topic)

2 Likes