I'm writing a plugin that has a custom page for displaying user stats: example.com/user/admin/
has a custom permalink structure that takes the reader to the /user/
page and display the data for the 'admin' user. Meanwhile, example.com/user/
should just return a list of all registered users. What I have done (that works) is have a code something like this:
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');
And then repeat an almost identical code for the other filters like the_content
and document_title_parts
.
What I want to know is how I can simplify this down a bit by having the filters in the condition rather than the condition in the filters. Something like this:
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
}