template_redirect
is usually a good action to hook a custom callback to, when you want to conditionally add or remove template actions / parts for the current request / view as the use has been identified, the WP object is set up, and WP is getting ready to determine which template to load.
You could use this action to check, if the request is for the home page (front page) and if it is the first time for the current user. This information could be saved as a separate user meta data. For example like this,
// use a custom callback to check and set home page first visit flag to user
add_action('template_redirect', 'prefix_check_first_home_page_visit', 1); // mind the priority
function prefix_check_first_home_page_visit() {
// Is home page
if ( ! is_front_page() ) {
return;
}
// Get user
$user = wp_get_current_user();
// Only logged in users
if ( ! $user->exists() ) {
return;
}
// Get user meta for home page visit
$visited_home_meta_key = 'home_page_first_visit'; // change as needed
$has_visited_home = get_user_meta(
$user->ID,
$visited_home_meta_key,
true
);
// Check, if user has already visited home page
if ( $has_visited_home ) {
return;
}
// Save first visit to user meta
update_user_meta(
$user->ID,
$visited_home_meta_key,
time() // e.g. timestamp when the first visit happened, change as needed
);
// Trigger later action
add_filter( 'is_home_page_first_visit', '__return_true' );
}
I got fancy above and used a custom filter at the end of the first callback to trigger the callback below, which takes care of adding the modal html to the template. This way the code is separated into smaller pieces, which makes it easier to manage and change later.
// A separate function for enabling the modal
add_action('template_redirect', 'prefix_show_home_page_first_visit_modal', 10); // mind the priority
function prefix_show_home_page_first_visit_modal() {
// Trigger modal printing conditionally
if ( apply_filters( 'is_home_page_first_visit', false ) ) {
// Print the modal html to the site footer for example
add_action('wp_footer', 'prefix_render_home_page_first_visit_modal');
}
}
function prefix_render_home_page_first_visit_modal() {
// Get template part or echo html here
}