So, I found a solution that seems to work great and as expected:
function custom_username_links_modify_links($content)
{
global $post;
$landing_page_id = get_option('custom_username_links_landing_page');
$registration_page_id = get_option('custom_username_links_registration_page');
if ($post && $post->ID == $landing_page_id) {
$url_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$url_parts = explode("https://wordpress.stackexchange.com/", trim($url_path, "https://wordpress.stackexchange.com/"));
if (count($url_parts) > 1) {
$element = $url_parts[1];
$custom_username = get_user_meta(get_current_user_id(), 'custom_username', true);
if (!empty($custom_username) && strpos($element, $custom_username) === 0) {
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
$href = $link->getAttribute('href');
if (custom_username_links_is_safe_url($href)) {
$url = rtrim($href, "https://wordpress.stackexchange.com/");
$newHref = $url . "https://wordpress.stackexchange.com/" . $element;
$link->setAttribute('href', $newHref);
}
}
$content = $dom->saveHTML();
} else {
// Weiterleitung auf die Registrierungsseite, wenn custom_username nicht übereinstimmt
if (!empty($registration_page_id)) {
wp_redirect(get_permalink($registration_page_id));
exit;
}
}
}
}
return $content;
}