Using WordPress ‘add_link’ PHP action

The add_link WordPress PHP action fires after a link was added to the database.

Usage

add_action('add_link', 'your_function_name');
function your_function_name($link_id) {
    // your custom code here
}

Parameters

  • $link_id (int): ID of the link that was added.

More information

See WordPress Developer Resources: add_link

Examples

Log when a new link is added with the link ID.

add_action('add_link', 'log_link_addition');
function log_link_addition($link_id) {
    $log_message = "A new link with ID: " . $link_id . " was added.\n";
    file_put_contents('link_log.txt', $log_message, FILE_APPEND);
}

Send an email notification to the site administrator when a new link is added.

add_action('add_link', 'email_admin_on_link_add');
function email_admin_on_link_add($link_id) {
    $admin_email = get_option('admin_email');
    $subject = "New link added to your website";
    $message = "A new link with ID: " . $link_id . " was added.";
    wp_mail($admin_email, $subject, $message);
}

Keep a count of the total number of links added.

add_action('add_link', 'increment_link_counter');
function increment_link_counter($link_id) {
    $link_count = get_option('link_count');
    update_option('link_count', ++$link_count);
}

Add link ID to a custom post meta

Add the link ID to a custom post meta.

add_action('add_link', 'add_link_id_to_post_meta', 10, 1);
function add_link_id_to_post_meta($link_id) {
    $post_id = 1; // Replace with the desired post ID
    add_post_meta($post_id, 'added_link_id', $link_id);
}

Automatically change the status of a newly added link to ‘draft’.

add_action('add_link', 'change_link_status_to_draft');
function change_link_status_to_draft($link_id) {
    $link_data = array(
        'link_id' => $link_id,
        'link_visible' => 'N',
    );
    wp_update_link($link_data);
}