Function and usage of links_add_base_url() in wordpress

Question

Answers ( 1 )

    0
    2024-01-09T00:35:00+00:00

    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.

    Function:

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

    Description:

    • 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.

    Parameters:

    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 "https://www.example.com", and there is a relative link in $content like <a href="/page">, it will be transformed to <a href="https://www.example.com/page">.

    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').

    Return:

    • 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 = 'https://www.example.com';
    $processed_content = links_add_base_url($content, $base);
    
    // Now, $processed_content will be:
    // '<a href="https://www.example.com/about">About Us</a> <img src="https://www.example.com/logo.png">'
    

    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