I am asking in the last instance because I am totally confused after not being able to invoke custom javascript functions for 2 days straight. I am new to Wordpress plugin developmnet as my background is Java and NodeJS and I simply can't understand why my code is not working.
I want to append a script in the html head based on the success event of a login, logout, and some other stuff. So I thought I could hook into the wp_registration
, wp_login
function and so on, enrich some data for the call and send this to a custom javascript. However the custom javascript is only invoked when I am calling the php function in the wp_head
hook or by doing add_action ('wp_enqueue_scripts', 'my_function' );
and never in the hook function where I need the invocation.
For testing purposes I have installed a clean Wordpress instance and have added the following function in my plugin:
function my_function() {
wp_register_script( 'custom-script', plugin_dir_url( __FILE__ ) . 'hook-test.js' );
wp_enqueue_script('custom-script');
$testVars = array(
'test' => __('I should see something!'),
);
wp_localize_script('custom-script', 'test_script_vars', $testVars);
}
Now how can I use this in the form (or with an analogous functionality): add_action('wp_login', 'my_function');
?
The javascript is never executed. But when I am doing
add_action('wp_head', 'my_function');
and add_action ('wp_enqueue_scripts', 'my_function');
it is...
I am welcoming any explanation and advice. Can't imagine this is so hard to achieve...