The “My Account” page in WooCommerce is a central hub where users manage their profiles, view order history, and update account details. Customizing the page title can provide a personalized touch and improve the user experience. In this guide, we’ll walk you through the steps to change the “My Account” page title to include the user’s name, creating a more welcoming and engaging experience for your customers.
/**
* Snippet Name: Customizing the "My Account" Page Title
* Snippet Author: wpsnippets.dev
*/
// Define a function to customize the My Account page title with the user's name
function wps_custom_my_account_title_with_name( $title, $id = null ) {
if ( is_account_page() && is_user_logged_in() && ! is_admin() && ( $id === wc_get_page_id( 'myaccount' ) ) ) {
$current_user = wp_get_current_user(); // Get the current logged-in user
$user_name = $current_user->display_name;
$title = 'Welcome, ' . $user_name . ' To Your Account'; // Custom title with user's name
}
// Check if it is the account page, not in admin, and matches the current page ID
elseif ( is_account_page() && ! is_admin() && ( $id === wc_get_page_id( 'myaccount' ) ) ) {
$title = 'Your Account'; // Default title for logged-out users
}
return $title; // Return the modified or default title
}
add_filter( 'the_title', 'wps_custom_my_account_title_with_name', 10, 2 );
Code Explanation
- The function wps_custom_my_account_title_with_name takes two parameters: $title (the current page title) and $id (the ID of the current page).
- It verifies certain conditions, such as if it’s on the account page and if the user is logged in. It matches the current page ID with the My Account page ID.
- If all conditions are met, it gets the current user’s display name and constructs a custom title welcoming the user to their account.
- If the user is not logged in or the conditions are not met, it sets a default title for the My Account page.
- The add_filter() function is used to hook the wps_custom_my_account_title_with_name function into the title rendering process.