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

时间:2016-08-06 13:46:09

标签: php wordpress

我的WordPress网站使用一个默认的“帖子”和“书籍”自定义帖子。我为不同的帖子类型设置了两种不同的存档页面设计(ile.author.php和books-archive.php)。

现在,我想创建一个自定义用户个人资料页面,其中包含两个链接,“按用户分类的所有帖子”和“按用户分类的所有书籍”。我当前的用户归档页面如下所示;

xxxxxxx.com/author/nilanchala

有人可以帮我如何创建按帖子类型过滤的两个作者存档页面吗?一个用于“邮政”,另一个用于“书籍”?

请不要建议任何插件。

1 个答案:

答案 0 :(得分:1)

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

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

例如,您必须重置固定链接才能使新的重写规则生效, 最好在类和自定义插件中创建,这样您就可以简单地调用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文件作为模板在该自定义URL上加载自定义查询,并使用template_include过滤器加载模板,如果url / request包含query_type=all_post

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文件上的任何内容。

现在您已拥有自定义网址和自定义php文件,您可以开始在php文件中创建自定义查询,以根据user_nicename / author_name查询帖子类型,

e.g。

<?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';
}

我不确定为什么您需要为所有帖子构建自定义查询,因为默认作者个人资料会加载所有默认帖子。

相关问题