Edit page with shortcode that uses wp_enqueue_script
-
My plugin converts a shortcode to some HTML code and links a JavaScript file. Simplified code:
add_shortcode('xxx', 'xxx_handler'); function xxx_handler($atts) { wp_enqueue_script('xxx-script', 'xxx', $deps, NULL, true); return '<div id="xxx" />'; }
The script uses getElementById(‘xxx’) to find the <div> and then performs some actions on it. This works fine in WP4 and in the WP5 front-end, but when editing a page with this shortcode in the WP5 back-end, the script alerts that it cannot find the <div>. It looks like the Gutenberg editor treats the editor as a front-end (causing the enqueued script to be run, in the footer), but does not render the shortcode itself???
My questions are:
- Am I doing something wrong in my shortcode handler?
- If not, is it a bug in Guttenberg?
- Can I do something to prevent this from happening?
P.S. I do not want to convert the shortcode to a Gutenberg Block (yet), because I already have a web page that generates the shortcode which can be used in WordPress and Joomla.
P.P.S. The current version of my plugin does not yet use the wp_enqueue_script but includes a <script> tag in the return statement, which does not cause any problems in WP5. But I need to use wp_enqueue_script to indicate an optional jQuery dependency.
- The topic ‘Edit page with shortcode that uses wp_enqueue_script’ is closed to new replies.