How to add custom javascript into <head> from custom plugin

I wrote a plugin but it keeps adding custom javascript into section not into section of every page.
Can anyone help me or give me a hint how to add js into section?

public constructor {
    add_action( 'init', array( $this, 'custom_js_register' ) );
    add_action( 'wp_head', array( $this,  'custom_js_print' ) );
}

function custom_js_register() {
    wp_register_script('custom_button', 'http://xxx.xxx.xxx/js/Button.js');
}

function custom_js_print() {
    wp_enqueue_script('custom_button');
}           

also instead of just loading js, I want to be able to do something like this.

<script type="text/javascript" src="http://xxx.xxx.xxx/js/Button.js" charset="UTF-8">
</script>

Related posts

1 comment

  1. You must use the hook to enqueue the scripts in WordPress.
    Use the hook wp_enqueue_scriptsfor the front end and admin_enqueue_scripts for the back end side.

    If you are enqueueing scripts and styles, you will want to use one of these three hooks:

    1. wp_enqueue_scripts (for the frontend)
    2. login_enqueue_scripts (for the
      login screen)
    3. admin_enqueue_scripts (for the admin dashboard)

    It is enough to use one method for register and enqueue of scripts. The difference is the benefit for other developers to de-register the script.

    public constructor() {
    
        add_action( 'wp_enqueue_scripts', array( $this,  'custom_js_register' ) );
    }
    
    public function custom_js_register() {
    
        wp_register_script( 'custom_button', 'http://xxx.xxx.xxx/js/Button.js' );
        wp_enqueue_script( 'custom_button' );
    
    }
    

    Als the hint to not use the static address, with http. It is better to use the wp function plugins_url. Also a example:

        wp_register_script( self::$handle,
               plugins_url( 'js/', __FILE__ ) . 'Button.js'
        );
    

Comments are closed.