Adding script, via plugins, in the admin head

Viewed 434

I've made a Wordpress plugin, and I'm trying to add javascript to the admin head. I've tried but couldn't managed to do it, could anyone help? Bellow is what I was going with:

  function __construct() {        
    add_action('wp_head', 'wpb_hook_javascript');
  }

function wpb_hook_javascript() {
?>
    <script>
      // javscript code 
    </script>
<?php

}

4 Answers

Note: this would only apply on the frontend. See @amarinediary's answer for the correct Admin implementation.

Your code to add the hook is currently inside of a __construct() function, which would only be triggered automatically if the plugin is a PHP Class. Try taking the add_action hook out of that and putting it at the same level as the other function.

add_action('wp_head', 'wpb_hook_javascript');

function wpb_hook_javascript() {
?>
    <script>
      // javscript code 
    </script>
<?php

this works!

add_action( 'wp_head', array( $this, 'function_name' ));

You can add a function (preferably in the root of your plugin directory) via 'admin_head', like so:

function my_custom_admin_script() {

    // get the current files folder name.
    $my_plugin_name = trim( dirname( plugin_basename( __FILE__ ) ), '/' );

    // get the plugin directory and add folder name.
    $my_plugin_directory = plugins_url() . '/' . $my_plugin_name;

    // enqueue script.
    // See https://developer.wordpress.org/reference/functions/wp_enqueue_script/
    wp_enqueue_script( 'my-script-name-reference', $my_plugin_directory . '/js/my-script.js', array( 'jquery' ), filemtime( $my_plugin_directory . '/js/my-script.js' ), true );

};
add_action( 'admin_head', 'my_custom_admin_script' );

Change /js/script.js to where you script is in your plugin structure.

This will then load the script on WordPress Admin screens - but not the Block Editor. If you want to attach a script in the block editor you should replace admin_head with enqueue_block_editor_assets - see the docs.

You need OOP structured solution which is following.

class testing {

public function __construct() {
   add_action( 'admin_head', array($this, 'admin_script'), 10 );
}

public function admin_script() {
  if ( is_admin() ) {
    echo '<script type="text/javascript">

    </script>';
  };
}

}  

// class object/instance 
  new testing();
Related