After creating a custom WordPress post type (For example: portfolio), you can see a list of all portfolios by simply going to the page – site.com/portfolio. The file archive.php is responsible for their output.
What if we want to display post of the portfolio type only of a certain user? The author’s archive file – author.php will help us with this:
- To do this, create a new file in the root directory of your theme and name it author-portfolio.php (Replace portfolio with your post type);
- Copy the contents of author.php into your author-portfolio.php file
Agree, such a url does not look very good and is not practical.
How chenge URL-s to user friendly
Our goal is to bring the url site.com/author/authorlogin/?post_type=portfolio to site.com/portfolio/authorlogin which is much more understandable and practical.
Add the code below to your function.php file:
function custom_rewrite_rules() { add_rewrite_rule( '^portfolio/([^/]+)/?$', 'index.php?author_name=$matches[1]&post_type=portfolio', 'top' ); } add_action('init', 'custom_rewrite_rules'); function custom_author_link($link, $author_id, $author_nicename) { $author = get_user_by('id', $author_id); if ($author && $author->user_nicename === $author_nicename) { return home_url(user_trailingslashit('portfolio/' . $author_nicename)); } return $link; } add_filter('author_link', 'custom_author_link', 10, 3); function custom_flush_rewrite_rules() { flush_rewrite_rules(); } add_action('after_switch_theme', 'custom_flush_rewrite_rules');
сustom_rewrite_rules function:
Adds a rewrite rule for portfolio post archive URLs.
^portfolio/([^/]+)/?$ is a regular expression to match a URL. ([^/]+) is responsible for capturing the value (username) from the URL.
index.php?author_name=$matches[1]&post_type=portfolio – Tells WordPress how to handle URLs. In this case, this is a request for an archive of “portfolio” records of a specific user.
Custom_author_link function: used to change the default author link to include the path we created.
home_url(user_trailingslashit(‘portfolio/’ . $author_nicename)) – builds a URL using the user’s nickname and appends it to “portfolio/“.