0

So I want to create a custom template file for my user profile page something like this URL http://localhost/wordpress/user/username.

Here you can see I have created a new page in Admin with this permalink user and I have created a new file in my theme directory at theme/user/page-{slug}.php and below is my code for this file.

<?php 

/*
    Template Name: User Profile
*/
wp_head();

?>

This is user profile page
<?php wp_footer(); ?>

I have also selected this template file in admin for this page and below is the screenshot of this newly created page.

enter image description here

But when I go to browser and try this URL http://localhost/wordpress/user/company , its giving me "Page Not Found" error.

Can someone guide me what I am doing wrong here ? How can I set a template based on this slug company here which has user in the URL.

4
  • Does a post with the slug company exist in the WordPress posts table, or is company a child of the user page? What is "username" - the username of a registered user on your site, or is it just a custom parameter used in your page template? Also, I know /user/username displays a user profile page, but what would /user/ display?
    – Sally CJ
    Mar 1 at 5:19
  • @SallyCJ its actually a page and company is just a slug and it wont be in posts table or in any table. Its just a custom parameter. /user/ without slug I will check and redirect if without slug. Mar 1 at 8:19
  • My apologies for the late reply, but I'm glad you already found a solution. All the best.
    – Sally CJ
    Mar 1 at 13:00
  • 1
    No worries dear .. Thanks for your support. Mar 1 at 13:31

1 Answer 1

0

Eventually I found out a solution. Below is how I have achieved this.

In my functions.php file, I have put below code.

add_filter('query_vars', 'add_user_var', 0, 1);
function add_user_var($vars){
    $vars[] = 'user';
    return $vars;
}

add_rewrite_rule('^user/([^/]+)/?$','index.php?pagename=user&user=$matches[1]','top');

This generally adds a rewrite rule if it finds user in the URL.

Now I have added a page template file name called as page-user.php and added below code to grab my query string.

$user = get_query_var('user');
echo $user;

I have created a page in backend admin with slug user and selected this template for this page.

Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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