Set Default Root-Relative URLs for Block Editor Links in WordPress

Yes, you can default to root-relative URLs in links created with the block editor in WordPress. To achieve this, you can use a combination of WordPress filters and functions. Follow these steps:

Functions.php Modification:

Open your theme’s functions.php file and add the following code snippet:

function root_relative_url($input) {
    preg_match('|https?://([^/]+)(/.*)|i', $input, $matches);
    if (!isset($matches[1]) || !isset($matches[2])) {
        return $input;
    }

    if ($matches[1] === $_SERVER['SERVER_NAME']) {
        return wp_make_link_relative($input);
    } else {
        return $input;
    }
}

function root_relative_urls() {
    ob_start('root_relative_url');
}

add_action('template_redirect', 'root_relative_urls');

Explanation:

  • The code above uses the template_redirect action hook to buffer the output and modify URLs.
  • Theroot_relative_url function checks if the URL’s domain matches the current server’s domain. If it does, it converts the URL to a root-relative URL using wp_make_link_relative()‘.

Testing:

  • After adding the code, create or edit a post using the block editor.
  • Insert or edit a link, and the URL should default to a root-relative format.

This method ensures that links created in the block editor will use root-relative URLs by default, providing cleaner and more portable links.

Was this helpful?

Thanks for your feedback!

Leave a Reply

Your email address will not be published. Required fields are marked *