User info variable through URL

87 views Asked by At

I am trying to create a page on wordpress which obtain specific info about a user, however I need to get the info from the URL. As an example i would like to get for "testuser" by getting username from a url such as:

http://www.site.com/book/testuser

I think it is a similar method to how the archive pages work but can't seem to find the code that does this.

Any help would be appreciated

Regards

1

There are 1 answers

2
Florian On BEST ANSWER

Introduction

To get informations from an url you should understand how WordPress uses url rewriting. If you use Permalinks the Rewrite API is used to map the url structure.

As example this is the rewrite rule for an url used to get all posts from an author:

'author/([^/]+)/?$' => 'index.php?author_name=$matches[1]'

The first part (left side of '=>') is an regular expression used to identify some parts of the url. The second part describes the target url generated by the rewrite rule. To keep it simple i will provide some examples for the rewrite rule:

www.example.com/author/johndoe => www.example.com/index.php?author_name=johndoe
www.example.com/author/VC10/ => www.example.com/index.php?author_name=VC10

You should use this rewriting mechanism to retrieve the needed information from the url.

Add rewrite rule

Supposed you want to call one specific page and evaluate the username during this call you should use a rewrite rule similar to this one:

'^book/([^/]*)/?' => 'index.php?page_id=12&username=$matches[1]'

This rule will rewrite all calls to a url with a strucuture like www.example.com/book/USERNAME to the WordPress page with id 12 and will pass the USERNAME as GET parameter. To add this rule use the following code:

function my_add_rewrite_rule() {  
   add_rewrite_rule(  
      '^book/([^/]*)/?',  
      'index.php?page_id=12&username=$matches[1]',  
      'top'
   );  
}  
add_action( 'init', 'my_add_rewrite_rule' );

Register new query variable

After adding the rewrite rule you have to make WordPress aware of the new querystring variable by using the add_rewrite_tag function.

function my_register_rewrite_tag() {  
   add_rewrite_tag( '%username%', '([^/]*)');  
}  
add_action( 'init', 'my_register_rewrite_tag'); 

Now you can access the username by the $wp_query variable like this:

$wp_query->query_vars['film_title']

Further Informations

For more informations about WordPress rewriting you might read this tutorial.