这只是一个例子,你应该按照你想要的方式修改它,我们将使用自定义查询和重写规则来构建 url
您需要做的第一件事是为要显示的两个自定义查询创建重写规则。
例如,您必须重置永久链接才能使新的重写规则生效,
这最好在类和自定义插件中创建,这样您就可以简单地调用 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/请求包含 query_type=all_post 时使用 template_include 过滤器来加载模板,从而在该自定义 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=username 或yoursite.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';
}
我不确定为什么需要为所有帖子构建自定义查询,因为默认作者个人资料会加载所有默认帖子。