add_shortcode and inline script

Hi guys I need some help.

In my WordPress plugin, I use add_shortcode to create the plugin JavasScript constructor so an inline script is added and it seems that this is not allowed… and add_inline_script must be used.

The problem is that by the time the shortcodes are processed the header has already been assembled so it is impossible to use add_inline_script…

I tried a lot of things before writing here but nothing worked.

Please help!

Thank you!

I have figured it out eventually.

For others that might have this issue, you have to register a dummy script in the footer and then add the inline js there, it works…

as far I know dummy/extra unnecessary file(s) not allowed and reviewer will ask you to remove that file. So, in this case you have to use any existing js file for wp_add_inline_script

In this case, this is the only way since it returns a script… I saw this in another plugin that is approved and checked so it is ok.

I guess it depends on the case but in my case this is the only way.

lets try and give an update here.

Have you tried using has_shortcode to check for the presence of your shortcode and then contextually enqueuing your constructor based on the result? If you needed to get specific settings from the shortcode for the JS constructor you could embed them in a data tag on the HTML element maybe?

Yes, I tried but it does not work, the shortcode is not simple, it accepts multiple parameters and it has to be parsed… and doing it like this is too difficult and prone to error…

Also, has_shortcode is not working in page builders like Elementor… so this is a big issue.

I am waiting for the reviewer to see if it is good if not I will have to find another way.

Ok guys I managed to make it work with the same script no dummy!

I know in my last theme that it is allowed to enqueue front js files in the footer, has this changed?

yes you can use your enqueue js file in the footer.

Awesome.

Thank you!