1

The following code works as expected on my WordPress setup, but when I send it to my friend who is running a cPanel managed version of WordPress, the JavaScript never runs. I can inspect the DOM and see that the js-test div is inserted though, verifying that the php ran. Any thoughts on what might be causing this? Am I doing something improper with the way I am enqueuing the script? I'd ideally like to only enqueue the script if the plugin's shortcode is present on the page, to avoid an unnecessary request.

js-test.php

<?php
/*
Plugin Name:  JS Test
Description:  JS Test
Version:      1.0
License:      MIT
License URI:  https://opensource.org/license/mit
*/

add_shortcode( 'js_test', function( $atts, $content, $tag ) {
  add_action("wp_enqueue_scripts", function() {
    wp_enqueue_script('js-test', plugin_dir_url( __FILE__ ) . 'js-test.js');
  });

  return "<div id='js-test' />";                                                
});

js-test.js

document.addEventListener('DOMContentLoaded', function() {
  const target = document.getElementById("js-test");                            
  console.log('target: ', target);
  if (target == null) {
    return;
  }

  target.innerHTML = "hello!!!";
});

1 Answer 1

1

You should not use wp_enqueue_scripts hook inside your shortcode, instead you should directly add wp_enqueue_script() function like:

add_shortcode( 'js_test', 'js_test_shortcode' );

function js_test_shortcode( $atts, $content, $tag ) {
    wp_enqueue_script('js-test', plugin_dir_url( __FILE__ ) . 'js-test.js');
  
    return '<div id="js-test"></div>';    
}

It should work now.

Note that I added a closing tag for your DIV.

Sign up to request clarification or add additional context in comments.

1 Comment

This fixed it, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.