新版本的 WordPress 自定義頭部功能和自定義背景很像,自 3.4 版本後,為主題新增自定義頭部功能方法很簡單那,只需要往主題的 functions.php 中新增程式碼:

  1. add_theme_support( 'custom-header' );  

同樣的,你也可以使用一些引數來設定預設選項:

  1. $defaults = array(   
  2.     'default-image'          => '',   
  3.     'random-default'         => false,   
  4.     'width'                  => 0,   
  5.     'height'                 => 0,   
  6.     'flex-height'            => false,   
  7.     'flex-width'             => false,   
  8.     'default-text-color'     => '',   
  9.     'header-text'            => true,   
  10.     'uploads'                => true,   
  11.     'wp-head-callback'       => '',   
  12.     'admin-head-callback'    => '',   
  13.     'admin-preview-callback' => '',   
  14. );   
  15. add_theme_support( 'custom-header', $defaults );  

例項:設定一個預設的頭部影像,

  1. $args = array(   
  2.     'width'         => 980,   
  3.     'height'        => 60,   
  4.     'default-image' => get_template_directory_uri() . '/images/header.jpg',   
  5. );   
  6. add_theme_support( 'custom-header', $args );  

允許上傳新影像:

  1. $args = array(   
  2.     'width'         => 980,   
  3.     'height'        => 60,   
  4.     'default-image' => get_template_directory_uri() . '/images/header.jpg',   
  5.     'uploads'       => true,   
  6. );   
  7. add_theme_support( 'custom-header', $args );  

輸出一個大小可變的頭部影像:

  1. $args = array(   
  2.     'flex-width'    => true,   
  3.     'width'         => 980,   
  4.     'flex-width'    => true,   
  5.     'height'        => 200,   
  6.     'default-image' => get_template_directory_uri() . '/images/header.jpg',   
  7. );   
  8. add_theme_support( 'custom-header', $args );  

後臺的設定都做好了,前臺呼叫設定選項的方法:

  1. <img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="" />