Function and usage of links_add_base_url() in wordpress


Answers ( 1 )


    The links_add_base_url() function in WordPress is designed to add a base URL to relative links in the content you pass to it. This function is particularly useful when you want to ensure that all links in a piece of content correctly point to the intended destination, especially after changing the domain or path of your website.


    links_add_base_url( string $content, string $base, array $attrs = array('src', 'href') ): string


    • The primary purpose of this function is to modify relative links within the content by adding a specified base URL to them.
    • By default, the function works with attributes 'src' (source of an image, script, etc.) and 'href' (hyperlink reference), but you can customize which attributes it should apply to by using the $attrs parameter.


    1. $content (string, required): This is the string that contains the HTML or content in which the links are to be processed. The function will search this string for links.

    2. $base (string, required): This is the base URL that will be prefixed to the relative links found in $content. For example, if you set $base to "", and there is a relative link in $content like <a href="/page">, it will be transformed to <a href="">.

    3. $attrs (array, optional): This parameter specifies which attributes of the HTML tags in the content should be processed. By default, it is set to process the 'src' and 'href' attributes. If you want to process different or additional attributes, you can specify them in an array. For instance, if you want to include 'data-src' for lazy-loaded images, you could set it as array('src', 'href', 'data-src').


    • The function returns a string. This string is the modified version of $content where all the specified attributes ($attrs) of the links have been prefixed with the $base URL.

    Sample Usage:

    $content = '<a href="/about">About Us</a> <img src="/logo.png">';
    $base = '';
    $processed_content = links_add_base_url($content, $base);
    // Now, $processed_content will be:
    // '<a href="">About Us</a> <img src="">'

    In this example, the function takes a string $content containing an HTML snippet with relative links. It prefixes these links with the $base URL, ensuring that the links point to the correct absolute path on the specified domain.

Leave an answer