我正在编写一个插件,它有一个用于显示用户统计信息的自定义页面:example.com/user/admin/
具有自定义的永久链接结构,可将读者带到/user/
页面并显示“admin”用户的数据。同时example.com/user/
应该只返回所有注册用户的列表。我所做的(有效的)是有这样一个代码:
function user_heading_func($heading)
{
$post_slug=$post->post_name;
if( $post->post_name != "user" || !in_the_loop() ){
// Do nothing
} else if ($wp_query->query_vars["u"]) { // checks if user is defined in permalink
$heading = "User data on ";
$user = get_user_by("slug", $wp_query->query_vars["u"]);
$heading .= "" . $user->data->user_login;
} else {
$heading = "User list";
}
return $heading;
}
add_filter(\'the_title\', \'user_heading_func\');
然后对其他过滤器重复几乎相同的代码,如
the_content
和
document_title_parts
.
我想知道的是,如何通过在条件中设置过滤器而不是在过滤器中设置条件来简化这一过程。类似这样:
global $post;
global $wp_query;
if($post->post_name != "user"){ // Normal page
// Do nothing
} else if ($wp_query->query_vars["u"]) { // User page with defined user
$user = get_user_by("slug",$wp_query->query_vars["u"]);
$heading = "User data on ".$user->data->user_login;
$name = $user->data->user_login;
add_filter(\'document_title_parts\', function($title){ // Edit the <title> tag
$title["title"] = "(user)\'s profile";
return $title;
});
add_filter(\'the_title\', function($head){ // Edit the <h1> tag
$head = "(user)\'s profile";
return $head;
});
add_filter(\'the_content\', function($content){ // Edit the main body content
$content = "(user)\'s profile data content goes here";
return $content;
});
} else { // User page with no defined user
// Similar to if ($wp_query->query_vars["u"]) but with different outputs
}