【参考】https://www.kancloud.cn/jabber/wordpress/296797
【参考】How to Use the WordPress Custom Logo API
什么是自定义徽标
使用自定义徽标( Logo ),网站所有者可以上传其网站的图片,该图片可以放置在其网站的顶部。可以从管理面板中的“ 外观”>“页眉”上传。自定义徽标支持应先使用add_theme_support() 添加到主题中,然后使用the_custom_logo() 在主题中调用。自定义徽标是可选的,但是主题作者如果在其主题中包含徽标,则应使用此功能。
为主题添加自定义徽标支持
使用add_theme_support()将自定义徽标支持首先添加到您的主题中, :
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' );
参数:
height 预期徽标高度(以像素为单位)。自定义徽标也可以使用内置的图像尺寸,例如 thumbnail ,或使用add_image_size() 来注册自定义尺寸。 |
width 预期徽标宽度(以像素为单位)。自定义徽标也可以使用内置的图像尺寸,例如thumbnail ,或使用add_image_size() 来注册自定义尺寸 。 |
flex-height 是否允许灵活的高度。 |
flex-width 是否允许灵活的宽度。 |
header-text 要隐藏的元素的类。它可以在此处为构成页眉文本的所有元素传递一个类名数组,这些页眉文本可以用徽标替换。 |
然后the_custom_logo在主题中调用
自定义Logo是可选的,但如果主题作者在其主题中包含Logo,则应使用此功能。
// Custom logo.
$logo_width = 120;
$logo_height = 90;
// If the retina setting is active, double the recommended width and height.
if ( get_theme_mod( 'retina_logo', false ) ) {
$logo_width = floor( $logo_width * 2 );
$logo_height = floor( $logo_height * 2 );
}
add_theme_support(
'custom-logo',
array(
'height' => $logo_height,
'width' => $logo_width,
'flex-height' => true,
'flex-width' => true,
)
);
使用after_setup_theme钩子,以便在主题加载后注册自定义Logo支持。
在主题中显示自定义徽标
可以使用the_custom_logo()函数在主题中显示自定义徽标。
如何判断是否上载logo:
<?php if ( has_custom_logo() ) : ?>
<div class="site-logo"><?php the_custom_logo(); ?></div>
<?php endif; ?>
通常,徽标会添加到header.php主题文件中,但也可以在其他位置。
自定义徽标模板标签
上载logo
使用自定义Logo可以让网站所有者上传他们网站的图片,这些图片可以放在他们网站的顶部。 它可以从您的管理面板中的 自定义-站点身份-图标 上传。
提示:建议的图片尺寸:150 x 30像素。
要经过裁剪图片
如果设置flex-width和flex-height为true,大小是不能调整的。
如下所示:
这个150 x 30像素 是哪里定义的呢?
$defaults = array(
'height' => 30,
'width' => 150,
'flex-width' => true/false,
'flex-height' => true/false,
);
add_theme_support( 'custom-logo', $defaults );
判断是否上载了logo
判断:
<?php if ( has_custom_logo() ) : ?>
<div class="site-logo"><?php the_custom_logo(); ?></div>
<?php endif; ?>
考虑兼容性
包装在一个function_exists()调用中,以保持与旧版本WordPress的向后兼容性,如下所示:
if ( function_exists( 'the_custom_logo' ) ) {
the_custom_logo();
}
相关函数
要管理在前端显示自定义Logo,可以使用以下三个模板标签:
- get_custom_logo() – 返回自定义Logo的标记。
- the_custom_logo() – 显示自定义Logo的标记。
- has_custom_logo() – 返回一个布尔值true/false,是否设置了自定义徽标。