The links_add_base_url() WordPress PHP function adds a base URL to relative links in the given content. By default, it supports the ‘src’ and ‘href’ attributes, but this can be changed via the third parameter.
Table of contents
Usage
$updated_content = links_add_base_url( $content, $base, $attrs );
Parameters
$content(string) (Required): The string to search for links in.$base(string) (Required): The base URL to prefix to links.$attrs(array) (Optional): The attributes which should be processed. Default: array(‘src’, ‘href’)
More information
See WordPress Developer Resources: links_add_base_url
Examples
Add Base URL to Image Sources
This example adds a base URL to the ‘src’ attribute of image tags in the given content.
$content = '<img src="image.jpg">'; $base_url = 'https://example.com/'; $updated_content = links_add_base_url( $content, $base_url ); // Result: '<img src="https://example.com/image.jpg">'
Add Base URL to Anchor Tags
This example adds a base URL to the ‘href’ attribute of anchor tags in the given content.
$content = '<a href="page.html">Visit Page</a>'; $base_url = 'https://example.com/'; $updated_content = links_add_base_url( $content, $base_url ); // Result: '<a href="https://example.com/page.html">Visit Page</a>'
Customize Attributes to Process
This example demonstrates how to customize the attributes that are processed by the links_add_base_url() function.
$content = '<img data-src="image.jpg">';
$base_url = 'https://example.com/';
$attrs = array('data-src');
$updated_content = links_add_base_url( $content, $base_url, $attrs );
// Result: '<img data-src="https://example.com/image.jpg">'
Add Base URL to Multiple Attributes
This example adds a base URL to both ‘src’ and ‘data-src’ attributes in the given content.
$content = '<img src="image.jpg" data-src="image.jpg">';
$base_url = 'https://example.com/';
$attrs = array('src', 'data-src');
$updated_content = links_add_base_url( $content, $base_url, $attrs );
// Result: '<img src="https://example.com/image.jpg" data-src="https://example.com/image.jpg">'
Add Base URL to a Mix of Anchor and Image Tags
This example adds a base URL to both ‘href’ attributes of anchor tags and ‘src’ attributes of image tags in the given content.
$content = '<a href="page.html">Visit Page</a> <img src="image.jpg">'; $base_url = 'https://example.com/'; $updated_content = links_add_base_url( $content, $base_url ); // Result: '<a href="https://example.com/page.html">Visit Page</a> <img src="https://example.com/image.jpg">'