什么是自定义标志?
使用自定义标志允许网站所有者上传图像到其网站的顶部。它可以从管理面板中的外观 > 头部进行上传。首先应使用 add_theme_support() 将自定义标志支持添加到您的主题中,然后在您的主题中使用 the_custom_logo() 调用它。自定义标志是可选的,但如果主题作者将其包含在主题中,则应使用该函数。
为您的主题添加自定义标志支持
要在您的主题中使用自定义标志,请在 functions.php 文件中添加以下内容:
add_theme_support( 'custom-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' ),
'unlink-homepage-logo' => true,
);
add_theme_support( 'custom-logo', $defaults );
}
add_action( 'after_setup_theme', 'themename_custom_logo_setup' );使用 after_setup_theme 钩子,以便在主题加载后注册自定义标志支持。
height
以像素为单位的预期标志高度。自定义标志也可以使用内置的图像尺寸(例如thumbnail),或使用add_image_size()注册自定义尺寸。width以像素为单位的预期标志宽度。自定义标志也可以使用内置的图像尺寸(例如
thumbnail),或使用add_image_size()注册自定义尺寸。flex-height
是否允许灵活的高度。flex-width是否允许灵活的宽度。
header-text要隐藏的元素类(组)。可以在此处传递一个类名数组,用于所有可由标志替换的构成头部文本的元素。
unlink-homepage-logo
如果参数unlink-homepage-logo设置为 true,当访客处于该页面时,使用get_custom_logo()或the_custom_logo()插入的标志图像将不再链接到主页。为了保持对已链接图像的样式,未链接的标志图像位于具有相同“custom-logo-link”类的span标签内。
在主题中显示自定义标志
可以使用 the_ 函数在主题中显示自定义标志。但建议将代码包装在 custom_logo()function_exists() 调用中以维护与旧版 WordPress 版本的向后兼容性,如下所示:
if ( function_exists( 'the_custom_logo' ) ) {
the_custom_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] ) . '" alt="' . get_bloginfo( 'name' ) . '">';
} else {
echo '<h1>' . get_bloginfo('name') . '</h1>';
}自定义标志模板标签
要管理在前端显示自定义标志,可以使用以下三个模板标签:
get_custom_logo() -返回自定义标志的标记。the_custom_logo() -显示自定义标志的标记。has_custom_logo() -返回布尔值 true/false,表示是否设置了自定义标志。