If you’re looking to add a welcoming touch to your WordPress Multisite network by displaying a modal for first-time users upon login, you’re in the right place. In this step-by-step guide, we’ll walk you through the process based on a user’s experience and the provided HTML code.

Step 1: Set User Meta

The first step is to set a user meta when a new user registers. This meta will act as a flag to determine whether the user is logging in for the first time.


function fyc_register_add_meta( $user_id ) {
add_user_meta( $user_id, '_new_user', '1' );
}
add_action( 'user_register', 'fyc_register_add_meta' );

This function adds the _new_user meta with a value of ‘1’ when a new user registers.

Step 2: Display Modal on First Login

The initial attempt to display the modal on first login used the wp_login action, but it had some issues. Instead, we can use the in_admin_footer action, which fires when the admin footer is being rendered.


function shapeSpace_first_user_login($user_login, $user) {
$new_user = get_user_meta( $user->ID, '_new_user', true );

if ( $new_user ) {
update_user_meta( $user->ID, '_new_user', '0' ); ?>

<div class="welcome-modal">
<header>
<h1>Welcome!</h1>
</header>
</div>

<?php }
}
add_action( 'in_admin_footer', 'shapeSpace_first_user_login' );

This code checks if the user is new and displays the welcome modal if needed.

Step 3: Troubleshoot and Optimize

The initial solution had a flaw related to the wp_login action. A user suggested using the in_admin_footer action directly for a more reliable solution. However, another user encountered issues with function arguments.


function fsc_new_user( $user_login, $user ) {
if ( $new_user = get_user_meta( $user->ID, '_new_user', true ) ) {
update_user_meta( $user->ID, '_new_user', '0' );
} else {
update_user_meta( $user->ID, '_new_user', '1' );
}
}
add_action( 'wp_login', 'fsc_new_user', 10, 2 );

function fsc_display_modal_first_login() {
if ( is_user_logged_in() ) {
$new_user = get_user_meta( get_current_user_id(), '_new_user', true );
if ( '1' === $new_user ) {
wp_enqueue_script( 'modal', plugin_dir_url( __FILE__ ) . 'js/flaunt-sites-core-welcome-modal.js', array(), 20190419, true );
update_user_meta( get_current_user_id(), '_new_user', '0' );
}
}
}
add_action( 'admin_footer', 'fsc_display_modal_first_login' );

This revised code uses get_current_user_id() to ensure compatibility and enqueues a JavaScript file to handle modal display.

Conclusion

By following these steps, you can enhance your WordPress Multisite user experience with a personalized welcome modal for first-time logins. Remember to customize the modal content and styles to suit your site’s branding. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *