Using WordPress ‘get_bookmarks’ PHP filter

The get_bookmarks WordPress PHP filter allows you to modify the list of bookmarks returned by WordPress.

Usage

add_filter('get_bookmarks', 'your_custom_function', 10, 2);
function your_custom_function($bookmarks, $parsed_args) {
    // your custom code here
    return $bookmarks;
}

Parameters

  • $bookmarks (array) – The list of cached bookmarks.
  • $parsed_args (array) – An array of bookmark query arguments.

More information

See WordPress Developer Resources: get_bookmarks

Examples

Remove a specific bookmark by ID

Remove a specific bookmark from the list by its ID.

add_filter('get_bookmarks', 'remove_specific_bookmark', 10, 2);
function remove_specific_bookmark($bookmarks, $parsed_args) {
    $bookmark_to_remove = 42; // The ID of the bookmark you want to remove

    foreach ($bookmarks as $key => $bookmark) {
        if ($bookmark->link_id == $bookmark_to_remove) {
            unset($bookmarks[$key]);
        }
    }
    return $bookmarks;
}

Order the bookmarks list by link name alphabetically.

add_filter('get_bookmarks', 'order_bookmarks_by_name', 10, 2);
function order_bookmarks_by_name($bookmarks, $parsed_args) {
usort($bookmarks, function($a, $b) {
return strcmp($a->link_name, $b->link_name);
});
return $bookmarks;
}

Filter bookmarks by target

Filter the bookmarks list to only display bookmarks with a specific target attribute.

add_filter('get_bookmarks', 'filter_bookmarks_by_target', 10, 2);
function filter_bookmarks_by_target($bookmarks, $parsed_args) {
    $target_filter = '_blank'; // The target attribute to filter by
    return array_filter($bookmarks, function($bookmark) use ($target_filter) {
        return $bookmark->link_target == $target_filter;
    });
}

Add a custom attribute to bookmarks

Add a custom data-* attribute to the bookmarks list.

add_filter('get_bookmarks', 'add_custom_attribute_to_bookmarks', 10, 2);
function add_custom_attribute_to_bookmarks($bookmarks, $parsed_args) {
    foreach ($bookmarks as $bookmark) {
        $bookmark->link_custom_attribute = 'custom_value';
    }
    return $bookmarks;
}

Limit the number of bookmarks displayed

Limit the number of bookmarks displayed to a specific count.

add_filter('get_bookmarks', 'limit_bookmarks_count', 10, 2);
function limit_bookmarks_count($bookmarks, $parsed_args) {
    $limit = 5; // The maximum number of bookmarks to display

    return array_slice($bookmarks, 0, $limit);
}