Refine custom posts by author

I want to have a way of displaying a custom post archive for a particular author. I’m able to display custom posts for a category but not just the custom posts for a author. I already have a separate author page template displaying all the posts they have written divided by post type. I’m querying this using :

query_posts( 
  array( 
    'post_type' => 'custom_post_name', 
    'author'=>$curauth->ID 
  ) 
); 
while (have_posts()) : the_post();

Essentially I want a number of author templates pages for every author.

Related posts

Leave a Reply

1 comment

  1. Three steps need to be followed to accomplish it.

    1. Add rewrite rules

    add_action('generate_rewrite_rules', 'author_cpt_add_rewrite_rules');
    function author_cpt_add_rewrite_rules( $wp_rewrite ) 
    {
      $new_rules = array( 
         'author/(.+)/(.+)' => 'index.php?author='.$wp_rewrite->preg_index(1) .
                                '&post_type=' .$wp_rewrite->preg_index(2) );
    
      //​ Add the new rewrite rule into the top of the global rules array
      $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    }
    

    2. Redirect to specific templates

    function author_cpt_template_redirect() {
        global $wp_query;
        // check for the target request
        if (!empty($wp_query->query_vars['author']) && !empty($wp_query->query_vars['post_type'])) {
            // turn off 404 error
            $wp_query->is_404 = false;
    
            // include if template is available
            if(file_exists('author-'.$wp_query->query_vars['post_type'].'.php'))
                include('author-'.$wp_query->query_vars['post_type'].'.php');
            else if(file_exists('author.php'))
                include('author.php');
            else
                include('index.php');
    
            return;
        }
    
    }
    

    3. Query posts to populate the page or template

    add_action('template_redirect', 'author_cpt_template_redirect', 1);
    function query_author_cpts( $query ) {
        // check for the target request
        if (!empty($query->query_vars['author']) && !empty($query->query_vars['post_type'])) 
        {
            // query posts accordingly
            query_posts( array( 
                            'post_type' => $query->query_vars['post_type'],
                            'author_name' => $query->query_vars['author'],
                            'paged' => get_query_var( 'paged' ) )
                        );
        }
    }
    add_action( 'wp', 'query_author_cpts' );