Function and usage of edit_link() in wordpress


Answers ( 1 )


    The edit_link() function in WordPress is used to update or insert a link in the database. Here's a detailed explanation of its usage:

    Function Signature:

    edit_link( int $link_id ): int|WP_Error

    Function Purpose:

    • Primary Use: To update an existing link or insert a new link into the WordPress database.
    • Context: This function is typically used in the context of managing links in the WordPress Links Manager or similar custom functionality related to link management.


    • $link_id (int, optional): The ID of the link you want to edit.
      • Default Value: 0.
      • Behavior:
        • If $link_id is specified (not 0), the function attempts to update the link with that ID.
        • If $link_id is 0 or not specified, the function treats the operation as an insertion of a new link.

    How It Works:

    1. Fetching Data: The function relies on the $_POST global variable to fetch the data to be inserted or updated. This means that the data to be saved (like link URL, name, description, etc.) should be present in the $_POST array.
    2. Operation:
      • Update: If a valid $link_id is provided, the function updates the corresponding link's details in the database.
      • Insert: If $link_id is 0, it inserts a new link with the details provided in $_POST.

    Return Values:

    • On Success: Returns the link ID (int). For an update, it's the ID of the updated link. For an insert, it's the ID of the newly created link.
    • On Failure: Returns WP_Error object.

    Sample Usage:

    Updating an Existing Link:

    $link_id = 123; // Assume this is the ID of the link you want to edit
    $_POST['link_url'] = '';
    $_POST['link_name'] = 'Example Link';
    $_POST['link_description'] = 'This is an example link.';
    $result = edit_link( $link_id );
    if ( is_wp_error( $result ) ) {
        // Handle error
        echo $result->get_error_message();
    } else {
        echo "Link updated successfully. Link ID: " . $result;

    Adding a New Link:

    $_POST['link_url'] = '';
    $_POST['link_name'] = 'New Site';
    $_POST['link_description'] = 'A new link to be added.';
    $result = edit_link( 0 ); // 0 for adding a new link
    if ( is_wp_error( $result ) ) {
        // Handle error
        echo $result->get_error_message();
    } else {
        echo "New link added successfully. Link ID: " . $result;


    • It's important to ensure that the necessary data is available in the $_POST array before calling edit_link().
    • Proper validation and sanitization of the $_POST data are recommended to avoid security issues.
    • This function is part of WordPress's admin functionality, so it may not be available on the front end without including the appropriate admin files.

Leave an answer