WP模板阁数千套各行业Wordpress模板随你选,总有一款适合你的网站![收藏本站] 注册 登录

WordPress程序优化:模板主题js和css路径输出代码优化

        发布:WP模板阁 类型:wordpress教程 浏览:607 次

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


<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等函数,所以改进代码:


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

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

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


<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php wp_title( '_', true, 'right' ); ?></title>
<?php wp_head(); ?>
</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文件中用如下代码即可


function ashuwp_scripts_styles() {
//输出style.css文件
wp_enqueue_style( 'ashuwp_style', get_stylesheet_uri(), array(), '1.0' );
//输出其他路径的css文件
wp_enqueue_style( 'font-awesome', get_template_directory_uri().'/css/font-awesome.min.css', array(), '1.0' );
//输出自带的jquery
wp_enqueue_script( 'jquery' );
//输出其他路径的js
wp_enqueue_script( 'ashuwp_js', get_template_directory_uri().'/js/ashuwp.js', array(), '1.0', true);
}
add_action( 'wp_enqueue_scripts', 'ashuwp_scripts_styles' );