I have to add some scripts in the head part of our website whenever a login or registration of a user was successful. For the login and register forms we use the Ultimate Member plugin, which has a hook method um_user_login
and um_user_register
which I though I could use for that.
I.e. if a user login was successful, do an head.append(...)
in JavaScript.
However I am a NodeJS and Java developer and completely new to Wordpress plugin programming. I can't find a suitable solution so far for this easy sounding task.
My idea was to hook at the um_user_login
action and do something like:
add_action('um_user_login', 'add_tracking_after_login', 10);
function add_tracking_after_login() {
add_action('wp_head', function() {
echo '<script type="text/javascript" src="my_script.js"></script>';
});
}
However, I have tested this with different logging, but it seems like the hook function to wp_head is never executed (the function add_tracking_after_login
is, as I have tested this with logging as well). So I think, I cannot add an action to wp_head this way.
Is there any other way to achieve the requested functionality? Or am I doing the hooking wrong as I am new to WordPress plugin programming?
Edit: To keep confusion low, this is just one of several tasks the client has requested. I also need to react on successful registrations and on successful sent emails with our contact form. In these cases I can't find an analogous workaround as in the answer below of Harry SM. I need to react on success events of the plugins we use.
Thanks in advance and best regards
you can add a condition for logged in user under wp_head hook.
add_action('wp_head', 'add_tracking_after_login', 10);
function add_tracking_after_login() {
if ( is_user_logged_in() ) {
echo '<script type="text/javascript" src="my_script.js"></script>';
}
}