I wrote the following code in a standalone plugin, but it doesn't work
Please guide me how to modify the code, so the JS file is loaded.

Plugin Name: Copy post
class CopyPostApi{
    public  function __construct(){
        // Add assets
        add_action( 'wp_enqueue_scripts', array($this, 'load_assets'));
    public function load_assets()
            plugin_dir_url(__FILE__) . 'assets/main.js',
new CopyPostApi;

Note: I searched and used the suggested codes, but it didn't work

  • 1
    What doesn't work? Is the issue just that the script is not working? Have you confirmed that the <script> tag is being output? Jan 10 at 11:28
  • 1
    This looks like a synchronisation problem. What hook are you using to initialize the class in your plugin?
    – cjbj
    Jan 10 at 17:21

3 Answers 3


Your code seems to be fine, so I think the problem will rather be in your theme. Are you developing your own theme too? The wp_head function calls in those files, which were hooked to wp_enqueue_scripts. It should be in the theme between the head tags, similarly as you see here: https://developer.wordpress.org/reference/functions/wp_head/#comment-900

  • Thanks for your answer, I wrote this code to define the javascript file for the standalone plugin Jan 10 at 15:08

I had the same problem... the thing is that you are using wp_enqueue_scripts, but if you want to load it in admin panel you have to use admin_enqueue_scripts instead...

The function should be called using the wp_enqueue_scripts action hook if you want to call it on the front-end of the site, like in the examples above. To call it on the administration screens, use the admin_enqueue_scripts action hook.


1)check the location of javascript file it must in correct directory.

  1. The function is being called too early: The wp_enqueue_script function should be called after the wp_enqueue_scripts hook is fired. Make sure that you are calling this function in the correct hook.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.