There's quite a few issues here:
do_action('user_register', $user_id );
No need to fire the action yourself (especially with an undefined variable $user_id
) - the idea of actions & filters is that you "hook" your function to one, and then let WordPress trigger it when applicable.
function MY_Callback(){
$data['user_id'] = $user_id;
My_print_js($data);
}
Again $user_id
is undefined (null) - you need to accept it as a parameter in your function:
function MY_Callback( $user_id ) {
Same issue again with your second function - you call it with a parameter (as above), but then completely ignore it and try to use the global $data
- instead you want:
function My_print_js( $data /* Take the argument man! */ ) {
echo '<script>';
echo 'dlayer.push('.json_encode($data).')'
echo '</script>';
}
Now for the final catch: even if you apply everything above, your code is still unlikely to work, since there's no certainty as to when the user_register
action will fire - your code simply prints a <script>
tag whenever it runs, with no guarantee that it's within the context of a HTML document, or that it will even print (what if there's a redirect header immediately after?).
I would suggest the following approach, and then test that it works for the scenario in which user_register
fires where you need it:
function wpse_200441_user_register( $user_id ) {
global $wpse_200441_user_register;
// Store the user ID that just registered in a global so that the script
// function can access it later.
$wpse_200441_user_register = $user_id;
// Hook the script function
add_action( 'wp_footer', 'wpse_200441_script' );
}
add_action( 'user_register', 'wpse_200441_user_register' );
function wpse_200441_script() {
global $wpse_200441_user_register;
if ( ! empty( $wpse_200441_user_register ) ) {
$json = json_encode(
array(
'user_id' => $wpse_200441_user_register,
)
);
echo "<script>dlayer.push( $json );</script>";
}
}