新版本的 WordPress 自定義頭部功能和自定義背景很像,自 3.4 版本後,為主題新增自定義頭部功能方法很簡單那,只需要往主題的 functions.php 中新增程式碼:
- add_theme_support( 'custom-header' );
同樣的,你也可以使用一些引數來設定預設選項:
- $defaults = array(
- 'default-image' => '',
- 'random-default' => false,
- 'width' => 0,
- 'height' => 0,
- 'flex-height' => false,
- 'flex-width' => false,
- 'default-text-color' => '',
- 'header-text' => true,
- 'uploads' => true,
- 'wp-head-callback' => '',
- 'admin-head-callback' => '',
- 'admin-preview-callback' => '',
- );
- add_theme_support( 'custom-header', $defaults );
例項:設定一個預設的頭部影像,
- $args = array(
- 'width' => 980,
- 'height' => 60,
- 'default-image' => get_template_directory_uri() . '/images/header.jpg',
- );
- add_theme_support( 'custom-header', $args );
允許上傳新影像:
- $args = array(
- 'width' => 980,
- 'height' => 60,
- 'default-image' => get_template_directory_uri() . '/images/header.jpg',
- 'uploads' => true,
- );
- add_theme_support( 'custom-header', $args );
輸出一個大小可變的頭部影像:
- $args = array(
- 'flex-width' => true,
- 'width' => 980,
- 'flex-width' => true,
- 'height' => 200,
- 'default-image' => get_template_directory_uri() . '/images/header.jpg',
- );
- add_theme_support( 'custom-header', $args );
後臺的設定都做好了,前臺呼叫設定選項的方法:
- <img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="" />