Refine custom posts by author

时间:2012-12-17 作者:Josh

我想有一种为特定作者显示自定义后期存档的方法。我能够显示某个类别的自定义帖子,但不仅仅是作者的自定义帖子。我已经有了一个单独的作者页面模板,显示他们写的所有帖子,按帖子类型划分。我使用以下方式查询此信息:

query_posts( 
  array( 
    \'post_type\' => \'custom_post_name\', 
    \'author\'=>$curauth->ID 
  ) 
); 
while (have_posts()) : the_post();
本质上,我希望每个作者都有一些作者模板页面。

1 个回复
SO网友:M-R

要做到这一点,需要遵循三个步骤。

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\' );

结束

相关推荐