create a WordPress function to add the Current Username to the Navigation Menu

Home » Snippets » create a WordPress function to add the Current Username to the Navigation Menu
0

Created with:

Visibility: 

public

Creator: Jules Webb

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php
// This function creates a shortcode that returns the Current User First Name
function wpturbo_firstname_shortcode() {
    // Check if the current user is logged in
    if ( is_user_logged_in() ) {
        // Get the current user's first name
        $current_user = wp_get_current_user();
        $firstname = $current_user->user_firstname;
        // Return the current user's first name
        return $firstname;
    }
}
add_shortcode( 'current_firstname', 'wpturbo_firstname_shortcode' );

// Enable shortcodes in Navigation Menus
add_filter( 'wp_nav_menu_items', 'do_shortcode' );
				

This code block creates a new shortcode called [current_firstname] which returns the current user's first name using the wp_get_current_user() function. If the user is not logged in, the shortcode will not display.

Finally, the add_filter() function is used to enable shortcode parsing in menus.

This code can either be added to the theme's functions.php file or in a custom plugin. To display the first name in the Navigation Menu, simply add [current_firstname] to the menu item or description where you want the first name to appear.

Register an account to save your snippets or go Pro to get more features.