函数文档

get_site_icon_url()

💡 云策文档标注

概述

get_site_icon_url() 函数用于获取 WordPress 网站的站点图标 URL,支持指定尺寸、备用 URL 和多站点博客 ID。函数内部处理多站点切换逻辑,并可通过过滤器进行自定义。

关键要点

  • 函数返回站点图标的 URL 字符串,默认尺寸为 512 像素。
  • 参数包括可选的 $size(图标尺寸)、$url(备用 URL)和 $blog_id(博客 ID)。
  • 在多站点环境中,如果指定了 $blog_id 且不同于当前博客,函数会临时切换博客以获取图标。
  • 通过 get_option('site_icon') 获取站点图标 ID,并使用 wp_get_attachment_image_url() 生成 URL。
  • 提供 get_site_icon_url 过滤器,允许开发者修改返回的 URL。

代码示例

function get_site_icon_url( $size = 512, $url = '', $blog_id = 0 ) {
	$switched_blog = false;

	if ( is_multisite() && ! empty( $blog_id ) && get_current_blog_id() !== (int) $blog_id ) {
		switch_to_blog( $blog_id );
		$switched_blog = true;
	}

	$site_icon_id = (int) get_option( 'site_icon' );

	if ( $site_icon_id ) {
		if ( $size >= 512 ) {
			$size_data = 'full';
		} else {
			$size_data = array( $size, $size );
		}
		$url = wp_get_attachment_image_url( $site_icon_id, $size_data );
	}

	if ( $switched_blog ) {
		restore_current_blog();
	}

	/**
	 * Filters the site icon URL.
	 *
	 * @since 4.4.0
	 *
	 * @param string $url     Site icon URL.
	 * @param int    $size    Size of the site icon.
	 * @param int    $blog_id ID of the blog to get the site icon for.
	 */
	return apply_filters( 'get_site_icon_url', $url, $size, $blog_id );
}

注意事项

  • 函数自 WordPress 4.3.0 版本引入,适用于主题和插件开发。
  • 在多站点中使用时,注意切换博客可能影响后续代码,函数会自动恢复。
  • 如果未设置站点图标,函数返回备用 URL 或空字符串。

📄 原文内容

Returns the Site Icon URL.

Parameters

$sizeintoptional
Size of the site icon. Default 512 (pixels).

Default:512

$urlstringoptional
Fallback url if no site icon is found. Default empty.
$blog_idintoptional
ID of the blog to get the site icon for. Default current blog.

Return

string Site Icon URL.

Source

function get_site_icon_url( $size = 512, $url = '', $blog_id = 0 ) {
	$switched_blog = false;

	if ( is_multisite() && ! empty( $blog_id ) && get_current_blog_id() !== (int) $blog_id ) {
		switch_to_blog( $blog_id );
		$switched_blog = true;
	}

	$site_icon_id = (int) get_option( 'site_icon' );

	if ( $site_icon_id ) {
		if ( $size >= 512 ) {
			$size_data = 'full';
		} else {
			$size_data = array( $size, $size );
		}
		$url = wp_get_attachment_image_url( $site_icon_id, $size_data );
	}

	if ( $switched_blog ) {
		restore_current_blog();
	}

	/**
	 * Filters the site icon URL.
	 *
	 * @since 4.4.0
	 *
	 * @param string $url     Site icon URL.
	 * @param int    $size    Size of the site icon.
	 * @param int    $blog_id ID of the blog to get the site icon for.
	 */
	return apply_filters( 'get_site_icon_url', $url, $size, $blog_id );
}

Hooks

apply_filters( ‘get_site_icon_url’, string $url, int $size, int $blog_id )

Filters the site icon URL.

Changelog

Version Description
4.3.0 Introduced.