当我们使用wordpress开发主题的时候,通常需要注意一些用户体验小功能,自定义顶部图像功能对于成熟的网站来说至关重要,那今天就给大家分享下在开发wordpress主题时,自定义顶部图像的功能,执行起来超简单,相信每个人都能学会,无论你是否有代码基础,只要你了解wordpress主题的标准构架就可以完成。
1、添加主题支持
从 3.4 版本 开始, 主题必须在 functions.php 文件里使用 add_theme_support() 函数来添加自定义顶部的支持, 像这样:
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 );
2、范例
设置自定义顶部图像 设置一个默认顶部图像(宽980px和高60px):
$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 );
3、前台调用
<img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="" />
PS:主题可以在模板中通过get_header_image判断是否有顶部图像,通过header_image获得图像地址:
<?php if ( get_header_image() ) : ?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
<img src="<?php header_image(); ?>" class="header-image" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="" />
</a>
<?php endif; ?>
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2018 群英 版权所有 茂名市群英网络有限公司
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号-36 粤公网安备 44090202000006号 粤工商备P091701000595