Get Wordpress username to customize url

I am currently trying to get the current username to add it to the url. The user should be able to navigate to his own dashboard wich is located under domain.com/username. Is there a way to retrieve the username and add it as variable to the url?

Thank you!

Topic membership php urls permalinks Wordpress

Category Web


In addition to what the answer at Dec 31 '19 said, I think this answer combines multiple answers given on this site. But since this website likes reproduction instead of references, I'll give a possible solution - including to the question of today (1 hour ago, according to my current screen).

function prefixed_redirect() {
    global $wp;
    if ( home_url( $wp->request ) == 'your_url' )  { // or maybe something more specific.
        require_once TEMPLATEPATH . '/my-specific-template.php';
    }
}
add_action( 'template_redirect', 'prefixed_redirect' );

I have not tested this code, but it is backed by these references: https://stackoverflow.com/questions/51028362/what-is-the-alternative-of-serverhttp-host-and-serverrequest-uri-for and How to load a new template page according to a particular URL?.

Now in case of the menu addition, I have this example:

function prefixed_nav_menu_item( $items ) {
    $user = wp_get_current_user();
    $link = '<li><a href="' . get_permalink( $user>get( 'slug' ) ) . '">' . $user->get( 'login' ) . '</a></li>';
    $items = $items . $link;

    return $items;
}
add_filter( 'wp_nav_menu_items', 'prefixed_nav_menu_item' );

This is also untested, but according to https://developer.wordpress.org/reference/functions/wp_get_current_user/ and https://developer.wordpress.org/reference/classes/wp_user/ it will take you in the right direction.

It may be the case that your specific theme has a predefined function in formatting menu items, which you should look into (of which the theme template files are a good starting point).


You can only do that if the user is logged in (otherwise there is no "current" user). Depending on what your specific use case is, it would be something like this:

if ( is_user_logged_in() ) {

    global $current_user;
    $current_user = wp_get_current_user();

    // get the username:
    $username = $current_user->user_login;

    // set up the URL:
    $url = home_url( $username );
}

Here's the documentation on the core WP functions I used above:

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.