skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. I believe you need to check the hierarchy of wordpress files and how they work. I am not a pro, but for example doc says:

    page-{slug}.php – If the page slug is privacy, WordPress will look to
    use page-privacy.php.

    link: https://developer.wordpress.org/themes/basics/template-hierarchy/

    (there is a very nice diagram in the above link)

    Thus, WP looking for
    http://localhost/wordpress/user/page-company.php

    But, apart from the above, you need to create a custom post type call user either via plugin or via function php code in functions.php file of your theme

    You could check this link:
    https://wordpress.org/plugins/custom-post-type-ui/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search