Using WordPress ‘add_link()’ PHP function

The add_link() WordPress PHP function adds a new link to your WordPress website, using values provided in $_POST. This is particularly useful when you need to programmatically insert links based on user input.

Usage

The add_link() function is quite straightforward as it does not require any parameters. Here’s a basic example:

add_link();

This will create a new link using data from the global $_POST variable.

Parameters

The add_link() function doesn’t require any parameters.

More Information

See WordPress Developer Resources: add_link()

This function was deprecated in WordPress 2.1.0. It’s recommended to use wp_insert_link() instead for adding links.

Examples

In this example, we’ll use a form to get link data from a user, which is then used by add_link() to add the link to WordPress.

// Assume that a form submission has happened
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // The link data is in the $_POST array
    $_POST['link_name'] = 'OpenAI';
    $_POST['link_url'] = 'https://www.openai.com/';

    // Call the function to add the link
    add_link();
}

This example shows how to add a link with a custom relationship (XFN). The rel value ‘friend’ is set, indicating the linked site is a friend’s.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_POST['link_name'] = 'John';
    $_POST['link_url'] = 'http://johnsblog.com';
    $_POST['link_rel'] = 'friend';

    add_link();
}

Here, we add a link with a description and a target attribute set to ‘_blank’ to open in a new tab.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_POST['link_name'] = 'Google';
    $_POST['link_url'] = 'https://www.google.com';
    $_POST['link_description'] = 'Search engine';
    $_POST['link_target'] = '_blank';

    add_link();
}

This example demonstrates adding a link with an associated image.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_POST['link_name'] = 'OpenAI';
    $_POST['link_url'] = 'https://www.openai.com';
    $_POST['link_image'] = 'https://www.openai.com/logo.png';

    add_link();
}

In this case, we add a link associated with a category.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_POST['link_name'] = 'OpenAI';
    $_POST['link_url'] = 'https://www.openai.com';
    $_POST['link_category'] = 'AI Companies';

    add_link();
}

Remember, since add_link() is deprecated, it’s recommended to use wp_insert_link() for adding links in newer versions of WordPress.