如何为自定义文章类型创建作者存档页面


How to Create Author archive page for custom post types

我的WordPress网站使用一个默认的"post"answers"books"自定义帖子。我有两个不同的归档页面设计,用于不同的帖子类型(ile.author.php和books-archive.php(

现在,我想创建一个自定义的用户配置文件页面,其中有两个链接,"所有帖子按用户"answers"所有书籍按用户"。我当前的用户档案页面如下所示;

xxxxxxx.com/author/nilanchala

有人能帮我如何创建两个按帖子类型过滤的作者档案页面吗?一个是"Post",另一个则是"Books"?

请不要建议任何插件。

这只是一个例子,你应该按照你想要的方式修改它,我们将使用自定义查询和重写规则来构建url

您需要做的第一件事是为要显示的两个自定义查询创建重写规则。

例如,您必须重置permalink才能使新的重写规则生效,这最好在类和自定义插件中创建,这样您就可以简单地调用flush_rewrite_rules()函数在插件激活期间重置永久链接。

function _custom_rewrite() {
    // we are telling wordpress that if somebody access yoursite.com/all-post/user/username
    // wordpress will do a request on this query var yoursite.com/index.php?query_type=all_post&uname=username
    add_rewrite_rule( "^all-post/user/?(.+)/?$", 'index.php?query_type=all_post&uname=$matches[1]', "top");
}
function _custom_query( $vars ) {
    // we will register the two custom query var on wordpress rewrite rule
    $vars[] = 'query_type';
    $vars[] = 'uname';
    return $vars;
}
// Then add those two functions on thier appropriate hook and filter
add_action( 'init', '_custom_rewrite' );
add_filter( 'query_vars', '_custom_query' );

既然您已经构建了一个自定义URL,那么您就可以通过创建一个自定义.php文件作为模板,并使用template_include过滤器来加载模板(如果URL/request包含query_type=all_post (,从而在该自定义URL上加载自定义查询

function _template_loader($template){
    // get the custom query var we registered
    $query_var = get_query_var('query_type');
    // load the custom template if ?query_type=all_post is  found on wordpress url/request
    if( $query_var == 'all_post' ){
        return get_stylesheet_directory_uri() . 'whatever-filename-you-have.php';
    }
    return $template;   
}
add_filter('template_include', '_template_loader');

然后您应该能够访问yoursite.com/index.php?query_type=all_post&uname=usernameyoursite.com/all-post/user/username它应该显示您在php文件中放置的内容。

既然您有了自定义url和自定义php文件,就可以开始在php文件中创建自定义查询,以查询基于user_nicename/author_name、的帖子类型

例如

<?php 
// get the username based from uname value in query var request. 
$user = get_query_var('uname');
// Query param
$arg = array(
    'post_type'         => 'books',
    'posts_per_page'    => -1,
    'orderby'           => 'date',
    'order'             => 'DESC',
    'author_name'       => $user;
);
//build query
$query = new WP_QUery( $arg ); 
// get query request
$books = $query->get_posts();
// check if there's any results
if ( $books ) {
    echo '<pre>', print_r( $books, 1 ), '</pre>';
} else {
    'Author Doesn''t have any books';
}

我不知道为什么你需要为所有帖子构建一个自定义查询,因为默认的作者配置文件加载了所有默认的帖子。