I hope you can help. I have tried to follow this and am not able to get the desired result.

I am using a static WordPress page as the basis for displaying all user profiles on the front end.

That page is: mydomain.com/user-profile and the page has an id of 31848

When each user's profile is loaded on that page, the url looks like this (where '2053' is the ID of the current user being displayed):

mydomain.com/user-profile/?users_filter=2053

Instead I would like it to look like this:

mydomain.com/user-profile/username

I have tried to follow through and am unable to get this to work.

Any help would be very much appreciated.

Best wishes, Andrew

  • in the page you are grabbing the URL parameter? – David Lee Feb 17 '17 at 17:20
  • Thanks for your response, David. I'm not quite sure what you mean. I think the answer is yes. The parameter is users_filter and the 2053 (in my example) is the value returned this time, for the example user. Is that what you need to know? – Andrew Brown Feb 17 '17 at 17:22

The first step is to add a query var so WordPress will recognize it and parse its value in rewrite rules.

function wpd_query_vars( $query_vars ) {
    $query_vars[] = 'users_filter_name';
    return $query_vars;
}
add_filter( 'query_vars', 'wpd_query_vars' );

Next, add a rewrite rule to capture the requests and set the users_filter_name:

function wpd_user_rewrite_rule(){
    add_rewrite_rule(
        '^user-profile/([^/]*)/?',
        'index.php?page_id=31848&users_filter_name=$matches[1]',
        'top'
    );
}
add_action( 'init', 'wpd_user_rewrite_rule' );

Don't forget to flush rewrite rules after they change.

Then you can access the query var in the template and load that user:

if( $users_filter_name = get_query_var( 'users_filter_name' ) ){
    $user = get_user_by( 'slug', $users_filter_name );
    if( !empty( $user ) ){
        echo $user->ID; // your original users_filter value
    }
}
  • Thank you for this - I am almost there!The rewrite is working great and the new url (/user-profile-username) is correctly displaying the static content for the page with if 31848. However, the loop is returning the metadata for all users, not just the one referenced in the url. Do you know what could be the issue here? – Andrew Brown Feb 18 '17 at 20:40
  • Your users_filter var is no longer set to the ID of the user, you'll need to change that code to access the user's ID like in the last example with $user->ID. – Milo Feb 18 '17 at 21:56
  • Hi Milo, thanks for getting back to me. How can I do that yet still have the desired pretty url without the user ID in it? – Andrew Brown Feb 20 '17 at 9:01

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.