Support » Plugin: Gutenberg » 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:

    1. Am I doing something wrong in my shortcode handler?
    2. If not, is it a bug in Guttenberg?
    3. 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.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter Arnoud Klaren

    (@aklaren)

    As a workaround, I have passed an extra parameter to the script to indicate that it has been loaded using the WordPress shortcode, so the <div> should exists. If it doesn’t, I log the error to the console instead of alerting the end-user.

    This is of course a work around. Can somebody please tell me if the Gutenberg editor pretends to be in front-end mode causing the enqueued scripts to be loaded and if there is anything else that I can do to prevent that from happening? Thanks!

    By the way, I am using the WordPress 5.0 nightly builds, so everything should be up-to-date.

    Thread Starter Arnoud Klaren

    (@aklaren)

    Can somebody please tell me if the Gutenberg editor pretends to be in front-end mode causing the enqueued scripts to be loaded and if there is anything else that I can do to prevent that from happening? Thanks!

    @clorith? Anybody?

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Edit page with shortcode that uses wp_enqueue_script’ is closed to new replies.