WordPress自定义作者URL,如何在author.php获取用户信息?
Hey there! I can help you get that user info showing up correctly in your author.php template. Let's break this down:
First, confirm your link setup is correct
Your current code for generating user links is actually right—get_author_posts_url($member->ID) properly outputs the correct author archive URL for each user. The issue is likely how you're trying to fetch user data inside author.php.
How to fetch user info in author.php
WordPress automatically sets up the author context when loading the author archive, so you have two reliable ways to get the current user's details:
Method 1: Use get_queried_object() (Recommended)
This function grabs the main object of the current query, which in this case is the user object for the author being viewed. It's clean and avoids extra function calls:
// Get the current author's user object $current_author = get_queried_object(); // Check if we have a valid user object before outputting if ($current_author instanceof WP_User) { // Output user details with proper escaping for security echo '<h2>' . esc_html($current_author->display_name) . '</h2>'; echo '<p>Username: ' . esc_html($current_author->user_login) . '</p>'; echo '<p>Bio: ' . wpautop(esc_html($current_author->description)) . '</p>'; // Access custom user meta like this: // echo '<p>Location: ' . esc_html(get_user_meta($current_author->ID, 'user_location', true)) . '</p>'; }
Method 2: Use get_query_var() + get_userdata()
If you prefer to fetch by ID first, grab the author ID from the query variables, then pull the user data:
// Get the author ID from the current query $author_id = get_query_var('author'); // Fetch the user object using the ID $current_author = get_userdata($author_id); // Output details (same as above) if ($current_author) { echo '<h2>' . esc_html($current_author->display_name) . '</h2>'; // ... rest of your output }
Key Notes to Avoid Issues
- Always use escaping functions like
esc_html()orwp_kses_post()when outputting user data to prevent security risks (like XSS attacks). - If your theme has a custom
author-{nicename}.phptemplate, that will override the defaultauthor.phpfor specific users—double-check you're editing the right file. - Don't modify the main query in
author.php(like usingquery_posts()), which could break the author context. Stick toget_queried_object()to avoid this.
Give either method a try, and your user info should show up correctly!
内容的提问来源于stack exchange,提问作者jord49

