I’ve created an rewrite endpoint with the add_rewrite_endpoint function … here is the whole contruct:
// Register to query vars
add_filter( 'query_vars', 'add_query_vars');
function add_query_vars( $vars ) {
$vars[] = 'account';
return $vars;
}
// Add rewrite endpoint
add_action( 'init', 'account_page_endpoint' );
function account_page_endpoint() {
add_rewrite_endpoint( 'account', EP_ROOT );
}
// Account template
add_action( 'template_include', 'account_page_template' );
function account_page_template( $template ) {
if( get_query_var( 'account', false ) !== false ) {
return locate_template( array( 'account.php' ) );
}
return $template;
}
This works great so far when i enter a url like example.com/account/username … but the links in the site are still like example.com?account=username.
How do i redirect from the parameter version to rewritten version? Is it necessary to add a additional rewrite rule or is there any function that these links have to run through?
The account links on the site itself are created by this function:
function account_url( $user_id ) {
$user = get_userdata( $user_id );
return add_query_arg( 'account', strtolower( $user->user_login ), get_home_url() );
}
2 Answers
Rewrite rules only handle incoming requests, they aren’t involved in link generation.
The primary WordPress rewrite system is parsed internally with PHP, you won’t see any changes to an .htaccess
file when you add an endpoint. The basic .htaccess rules essentially say “If this isn’t a request for a physical file or directory on the server, then hand the request over to WordPress”.
Your account_url
function has to handle both “ugly” and “pretty” cases when it outputs the account URLs. We can look at the built in get_permalink
function to see how WordPress handles this, here’s an abbreviated version:
$permalink = get_option('permalink_structure');
if ( '' != $permalink ) {
// output a pretty permalink
} else {
// output an ugly permalink
}
The permalink_structure
option holds the chosen pattern if pretty permalinks are enabled, we know pretty permalinks are disabled if it’s empty.