本页目录
什么是自定义 Logo?
使用自定义 Logo 可以让网站所有者上传他们网站的图片,这些图片可以放在他们网站的顶部。 它可以从您的管理面板中的外观>标题上传。 应该使用 add_theme_support()将自定义徽标支持首先添加到您的主题中,然后 the_custom_logo 在主题中调用。 自定义 Logo 是可选的,但如果主题作者在其主题中包含 Logo,则应使用此功能。
官方文档:
the_custom_logo();https://developer.WordPress.org/reference/functions/the_custom_logo/
向您的主题添加自定义 Logo 支持
要在主题中使用自定义徽标,请将以下内容添加到您的 functions.php 文件中:
add_theme_support( 'custom-logo' );启用自定义 Logo 支持时,可以使用数组将参数传递给 add_theme_support()函数来配置五个参数:
function themename_custom_logo_setup() { $defaults = array( 'height' => 100, 'width' => 400, 'flex-height' => true, 'flex-width' => true, 'header-text' => array( 'site-title', 'site-description' ), ); add_theme_support( 'custom-logo', $defaults );}add_action( 'after_setup_theme', 'themename_custom_logo_setup' );使用 after_setup_theme 钩子,以便在主题加载后注册自定义 Logo 支持。
- height 预期 Logo 高度(以像素为单位) 自定义 Logo 还可以使用内置的图像大小,如缩略图,或使用 add_image_size()注册自定义大小。
- width 预期 Logo 宽度(以像素为单位) 自定义 Logo 还可以使用内置的图像大小,如缩略图,或使用 add_image_size()注册自定义大小。
- flex-height 是否允许灵活的高度。
- flex-width 是否允许灵活的宽度。
- header-text 要隐藏的元素的类。 它可以在这里传递一个类名称数组,用于构成标题文本的所有元素,可以由 Logo 代替。
在主题中显示自定义 Logo
可以使用 the_custom_logo()函数在主题中显示自定义徽标。 但是建议将代码包装在一个 function_exists()调用中,以保持与旧版本 WordPress 的向后兼容性,如下所示:
if ( function_exists( 'the_custom_logo' ) ) { the_custom_logo();}通常,Logo 会添加到主题的 header.php 文件中,但它也可以在其他地方。
如果要获取当前的标识 URL(或使用自己的标记)而不是默认标记,则可以使用以下代码:
$custom_logo_id = get_theme_mod( 'custom_logo' );$logo = wp_get_attachment_image_src( $custom_logo_id , 'full' );if ( has_custom_logo() ) { echo '<img src="'. esc_url( $logo[0] ) .'">';} else { echo '<h2>'. esc_attr( get_bloginfo( 'name' ) ) .'</h2>';}自定义 Logo 模板标签
要管理在前端显示自定义 Logo,可以使用以下三个模板标签:
- get_custom_logo() – 返回自定义 Logo 的标记。
- the_custom_logo() – 显示自定义 Logo 的标记。
- has_custom_logo() – 返回一个布尔值 true/false,是否设置了自定义徽标。