【參考】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,是否設置了自定義徽標。