WordPress主题优化(1): heaer.php的优化

阿树发现很多写wp主题的同学,代码不规范,效率不高,所以准备写一系列教程,把阿树在别的主题上看到的常见的不合理或者可以更优化地方贴出来,供大家参考。

header.php一般在主题中作为头部文件引入。

优化一. js和css路径的输出

header.php文件中,常见的问题(不是错误)就是在js和css文件的引入上,很多wp同学是在header.php中直接写上css或js的路径,如下:

  1. <script src="<?php bloginfo('stylesheet_directory'); ?>/js/theme.js" type="text/javascript" ></script>

问题:WordPress不推荐使用bloginfo的stylesheet_directory来输出主题的uri,为什么呢?

执行bloginfo('stylesheet_directory'),首先是调用get_bloginfo('stylesheet_directory'),然后get_bloginfo函数里面根据'stylesheet_directory'参数又调用get_stylesheet_directory_uri函数,或者调用get_template_directory_uri函数。

改进:WordPress官方文档也推荐直接使用get_template_directory_uri等函数,所以改进代码:

  1. <script src="<?php echo get_template_directory_uri(); ?>/js/theme.js" type="text/javascript" ></script>

更高级的用法:此处更高级的用法适用于你写的主题给别人用,或者发布给很多人用。

所有js和css使用wp_head钩子输出,wp默认主题也是这么做的。

  1. <!DOCTYPE html>
  2. <html <?php language_attributes(); ?>>
  3. <head>
  4. <meta charset="<?php bloginfo( 'charset' ); ?>">
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title><?php wp_title( '_', true, 'right' ); ?></title>
  7. <?php wp_head(); ?>
  8. </head>

解释:

在html标签中用language_attributes函数输出语言,适用于多语言环境,也可以直接写lang="zh-CN"或者lang="en-US"

使用bloginfo( 'charset' )输出编码,直接写出charset="UTF-8"也可。

title在新的wp主题里面标签也是不要的,直接用add_theme_support函数即可。

重点是wp_head函数,这个函数调用的各个钩子,可以输出title标签,可以输出js路径,可以输出css路径......

有了wp_head函数,在functions.php文件中用如下代码即可

  1. function ashuwp_scripts_styles() {
  2.   //输出style.css文件
  3.   wp_enqueue_style( 'ashuwp_style', get_stylesheet_uri(), array(), '1.0' );
  4.   //输出其他路径的css文件
  5.   wp_enqueue_style( 'font-awesome', get_template_directory_uri().'/css/font-awesome.min.css', array(), '1.0' );
  6.   //输出自带的jquery
  7.   wp_enqueue_script( 'jquery' );
  8.   //输出其他路径的js
  9.   wp_enqueue_script( 'ashuwp_js', get_template_directory_uri().'/js/ashuwp.js', array(), '1.0', true);
  10. }
  11. add_action( 'wp_enqueue_scripts', 'ashuwp_scripts_styles' );

End。

本篇教程之前的几篇教程是

本篇教程之后的几篇教程是

没有找到你要找的内容?你可以通过搜索你要找的内容,或者给我们留言。

已有9条评论

hoythan进行回复 取消回复