函数文档

wp_update_link()

💡 云策文档标注

概述

wp_update_link() 函数用于更新数据库中的链接。它通过合并现有链接数据和新提供的参数,并调用 wp_insert_link() 来执行更新操作。

关键要点

  • 参数 $linkdata 是一个必需数组,包含要更新的链接数据,参数定义与 wp_insert_link() 一致。
  • link_id 参数可选,用于指定要更新的现有链接 ID;如果未提供,函数可能基于其他数据操作。
  • 函数返回更新后的链接 ID(成功时)或 0/WP_Error(失败时)。
  • 内部实现先通过 get_bookmark() 获取现有链接,合并数据后调用 wp_insert_link() 完成更新。

代码示例

// 示例:更新一个链接
$linkdata = array(
    'link_id' => 123,
    'link_name' => '新链接名称',
    'link_url' => 'https://example.com'
);
$result = wp_update_link($linkdata);
if (is_wp_error($result)) {
    // 处理错误
} else {
    echo '更新成功,链接 ID: ' . $result;
}

注意事项

  • link_category 参数如果以数组形式提供且非空,会覆盖现有分类;否则保留原分类。
  • 函数内部使用 wp_slash() 对数据库数据进行转义,确保数据安全。
  • 更新操作依赖于 wp_insert_link(),因此需确保参数符合其要求。

📄 原文内容

Updates a link in the database.

Parameters

$linkdataarrayrequired
Link data to update. See wp_insert_link() for accepted arguments.

More Arguments from wp_insert_link( … $linkdata )

Elements that make up the link to insert.

  • link_id int
    Optional. The ID of the existing link if updating.
  • link_url string
    The URL the link points to.
  • link_name string
    The title of the link.
  • link_image string
    Optional. A URL of an image.
  • link_target string
    Optional. The target element for the anchor tag.
  • link_description string
    Optional. A short description of the link.
  • link_visible string
    Optional. 'Y' means visible, anything else means not.
  • link_owner int
    Optional. A user ID.
  • link_rating int
    Optional. A rating for the link.
  • link_rel string
    Optional. A relationship of the link to you.
  • link_notes string
    Optional. An extended description of or notes on the link.
  • link_rss string
    Optional. A URL of an associated RSS feed.
  • link_category int
    Optional. The term ID of the link category.
    If empty, uses default link category.

Return

int|WP_Error Value 0 or WP_Error on failure. The updated link ID on success.

Source

function wp_update_link( $linkdata ) {
	$link_id = (int) $linkdata['link_id'];

	$link = get_bookmark( $link_id, ARRAY_A );

	// Escape data pulled from DB.
	$link = wp_slash( $link );

	// Passed link category list overwrites existing category list if not empty.
	if ( isset( $linkdata['link_category'] ) && is_array( $linkdata['link_category'] )
		&& count( $linkdata['link_category'] ) > 0
	) {
		$link_cats = $linkdata['link_category'];
	} else {
		$link_cats = $link['link_category'];
	}

	// Merge old and new fields with new fields overwriting old ones.
	$linkdata                  = array_merge( $link, $linkdata );
	$linkdata['link_category'] = $link_cats;

	return wp_insert_link( $linkdata );
}

Changelog

Version Description
2.0.0 Introduced.