阿树发现很多写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

获取更多建站运营运维新知!互联网创业、前沿技术......
最新评论
水淀粉vdfv
有其他下载方式么,网站上的点击下载后没有任何反应,或者直接发给我一下?83835079@qq.com
你好,我的型号ELECOM WRC-X3200GST3,ARMv8 Processor rev 4构架,CPU mediatek/mt7622,找了很久没有找到
我的也是这样。一直无法确认ARCH架构,或是不支持。一直没办法用。不知道怎么办了
您好,现在安装上了,可是ssr plus+配置好节点也没用,一直都是未运行,节点是有效的; 另外那个passwall2一找开就提示"无法确认ARCH架构,或是不支持", 麻烦大佬帮忙看下是什么问题,谢谢!