php - Get Wordpress username to customize url

admin2025-01-08  4

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/username. Is there a way to retrieve the username and add it as variable to the url?

Thank you!

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!

Share Improve this question asked Dec 31, 2019 at 15:54 Niels KNiels K 11 bronze badge
Add a comment  | 

2 Answers 2

Reset to default 0

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:

  • wp_get_current_user()
  • home_url()

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).

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736268876a1309.html

最新回复(0)