Author Profile URL

I have 2 user roles. “photographer” and “subscriber”

I have set my author.php like this

Read More
<?php get_header(); 
    $thisauthor = get_userdata(intval($author));
    $author_user = $wp_query->get_queried_object();
        ?>
     <div id="main">
     <?php
   if (user_can($author_user, 'photographer')) { 
      get_template_part( 'author', 'photographer' ); }
   else if (user_can($author_user, 'subscriber')) { 
      get_template_part( 'author', 'subscriber' ); }
     ?>
   </div><!--/main-->
     <?php get_footer(); ?>

This is working great to show different profiles based on the user roles. However id like to change the url based on the roles.

Something like

http://xxx.xxx/subscriber/username/

http://xxx.xxx/photographer/username/

Any ideas on getting this done?

Related posts

1 comment

  1. To change all author URLs one would normally change the author base, however, since you want multiple author bases, we’ll have to do things a bit differently.

    There are two parts to this – The first part is getting WordPress to recognize incoming requests for your custom author pages and route them properly. To do this we’ll add two new rewrite rules that take anything after a request for subscriber/ or photographer/ and pass that as an author_name to the main query. WordPress will process these as is_author requests, just like normal author pages.

    function wpa_author_rewrite_rules(){
    
        add_rewrite_rule(
            'subscriber/([^/]+)/?$',
            'index.php?author_name=$matches[1]',
            'top'
        );
    
        add_rewrite_rule(
            'photographer/([^/]+)/?$',
            'index.php?author_name=$matches[1]',
            'top'
        );
    
    }
    add_action( 'init', 'wpa_author_rewrite_rules' );
    

    Note that rewrite rules will need to be flushed once after adding this code so they will take effect.

    The second part of this is for WordPress to generate the correct URLs when you use the API to output author URLs. Modifying WordPress output is typically done via a filter, as is the case here as well. We modify the output of functions that generate author URLs via the author_link filter. You’ll recognize the user_can function in use here to check if the $author_id has the subscriber or photographer roles, returning custom URLs for those cases.

    function wpa_author_link( $link, $author_id, $author_nicename ){
    
        if( user_can( $author_id, 'subscriber' ) ){
    
            return home_url( 'subscriber/' . $author_nicename . '/' );
    
        } elseif( user_can( $author_id, 'photographer' ) ) {
    
            return home_url( 'photographer/' . $author_nicename . '/' );
    
        }
    
        return $link;
    
    }
    add_filter( 'author_link', 'wpa_author_link', 10, 3 );
    

Comments are closed.