欢迎光临
我们一直在努力

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

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

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

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

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

<script class="string">"<?php bloginfo('stylesheet_directory'); ?>/js/theme.js" type=<span class="string">"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 class="string">"<?php echo get_template_directory_uri(); ?>/js/theme.js" type=<span class="string">"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' );

End。

文章来源于互联网:https://www.ashuwp.com/courses/wp%e4%bc%98%e5%8c%96/916.html

窗外天空
关注公众号『窗外天空』

获取更多建站运营运维新知!
互联网创业、前沿技术......

赞(0) 打赏
文章名称:《WordPress主题优化(1): heaer.php的优化》
文章链接:https://www.nixonli.com/298.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏