wordpress5.3 在有关wp_head() 和wp_footer()的使用

目录

如何使用wp_head()函数

如何去除多余的样式和脚本

如何添加自己的样式引用呢?


如何使用wp_head()和wp_footer()函数

wp_head()函数常见于html文档的head区域

wp_footer()函数常用于</body>结束前

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <?php wp_head(); ?>
</head>
<body>

<?php wp_footer(); ?>
</body>
</html>

网页运行后的源代码如下:


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel='dns-prefetch' href='//s.w.org' />
		<script type="text/javascript">
			window._wpemojiSettings = {"baseUrl":"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/72x72\/","ext":".png","svgUrl":"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/svg\/","svgExt":".svg","source":{"concatemoji":"http:\/\/localhost\/wordpress\/wp-includes\/js\/wp-emoji-release.min.js?ver=5.3.2"}};
			!function(e,a,t){var r,n,o,i,p=a.createElement("canvas"),s=p.getContext&&p.getContext("2d");function c(e,t){var a=String.fromCharCode;s.clearRect(0,0,p.width,p.height),s.fillText(a.apply(this,e),0,0);var r=p.toDataURL();return s.clearRect(0,0,p.width,p.height),s.fillText(a.apply(this,t),0,0),r===p.toDataURL()}function l(e){if(!s||!s.fillText)return!1;switch(s.textBaseline="top",s.font="600 32px Arial",e){case"flag":return!c([127987,65039,8205,9895,65039],[127987,65039,8203,9895,65039])&&(!c([55356,56826,55356,56819],[55356,56826,8203,55356,56819])&&!c([55356,57332,56128,56423,56128,56418,56128,56421,56128,56430,56128,56423,56128,56447],[55356,57332,8203,56128,56423,8203,56128,56418,8203,56128,56421,8203,56128,56430,8203,56128,56423,8203,56128,56447]));case"emoji":return!c([55357,56424,55356,57342,8205,55358,56605,8205,55357,56424,55356,57340],[55357,56424,55356,57342,8203,55358,56605,8203,55357,56424,55356,57340])}return!1}function d(e){var t=a.createElement("script");t.src=e,t.defer=t.type="text/javascript",a.getElementsByTagName("head")[0].appendChild(t)}for(i=Array("flag","emoji"),t.supports={everything:!0,everythingExceptFlag:!0},o=0;o<i.length;o++)t.supports[i[o]]=l(i[o]),t.supports.everything=t.supports.everything&&t.supports[i[o]],"flag"!==i[o]&&(t.supports.everythingExceptFlag=t.supports.everythingExceptFlag&&t.supports[i[o]]);t.supports.everythingExceptFlag=t.supports.everythingExceptFlag&&!t.supports.flag,t.DOMReady=!1,t.readyCallback=function(){t.DOMReady=!0},t.supports.everything||(n=function(){t.readyCallback()},a.addEventListener?(a.addEventListener("DOMContentLoaded",n,!1),e.addEventListener("load",n,!1)):(e.attachEvent("onload",n),a.attachEvent("onreadystatechange",function(){"complete"===a.readyState&&t.readyCallback()})),(r=t.source||{}).concatemoji?d(r.concatemoji):r.wpemoji&&r.twemoji&&(d(r.twemoji),d(r.wpemoji)))}(window,document,window._wpemojiSettings);
		</script>
		<style type="text/css">
img.wp-smiley,
img.emoji {
	display: inline !important;
	border: none !important;
	box-shadow: none !important;
	height: 1em !important;
	width: 1em !important;
	margin: 0 .07em !important;
	vertical-align: -0.1em !important;
	background: none !important;
	padding: 0 !important;
}
</style>
	<link rel='stylesheet' id='wp-block-library-css'  href='http://localhost/wordpress/wp-includes/css/dist/block-library/style.min.css?ver=5.3.2' type='text/css' media='all' />
<link rel='https://api.w.org/' href='http://localhost/wordpress/wp-json/' />
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://localhost/wordpress/xmlrpc.php?rsd" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://localhost/wordpress/wp-includes/wlwmanifest.xml" /> 
<meta name="generator" content="WordPress 5.3.2" />
</head>
<body>

<script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/wp-embed.min.js?ver=5.3.2'></script>
</body>
</html>

可以看出,wp_head()函数和wp_footer()函数可以引入CSS样式和JS脚本

如何去除多余的样式和脚本

毕竟wordpress程序是外国人开发的,wordpress程序代码中有很多对于国人来说不太实用的,有的甚至是多余的,从而影响了wordpress打开速度。所以,在我们开发wordpress CMS主题时,要对这些无用的东西进行去除。

把下面这段代码放到我们当前启用的wordpress主题的functions.php文件中:

function disable_emojis() {
    remove_action( 'wp_head', 'wp_generator' ); //移除WordPress版本
    remove_action( 'wp_head', 'rsd_link' ); //移除离线编辑器开放接口
    remove_action( 'wp_head', 'wlwmanifest_link' ); //移除离线编辑器开放接口
    remove_action( 'wp_head', 'index_rel_link' ); //去除本页唯一链接信息
    remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 ); //清除前后文信息
    remove_action( 'wp_head', 'start_post_rel_link', 10, 0 ); //清除前后文信息
    remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 ); //清除前后文信息
    remove_action( 'wp_head', 'feed_links', 2 ); //移除feed
    remove_action( 'wp_head', 'feed_links_extra', 3 ); //移除feed
    remove_action( 'wp_head', 'rest_output_link_wp_head', 10 ); //移除wp-json链
    remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); //头部的JS代码
   // remove_action( 'wp_head', 'wp_print_styles', 8 ); //emoji载入css
    remove_action( 'wp_head', 'rel_canonical' ); //rel=canonical
    remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 ); //rel=shortlink
    add_filter( 'wp_resource_hints', 'remove_dns_prefetch', 10, 2 ); //头部加载DNS预获取(dns-prefetch)
}
add_action( 'init', 'disable_emojis' );
//移除WordPress头部加载DNS预获取(dns-prefetch)
function remove_dns_prefetch( $hints, $relation_type ) {
    if ( 'dns-prefetch' === $relation_type ) {
        return array_diff( wp_dependencies_unique_hosts(), $hints );
    }
    return $hints;
}

我们再看看处理后的页面代码是个什么样式,如下图:


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style type="text/css">
img.wp-smiley,
img.emoji {
	display: inline !important;
	border: none !important;
	box-shadow: none !important;
	height: 1em !important;
	width: 1em !important;
	margin: 0 .07em !important;
	vertical-align: -0.1em !important;
	background: none !important;
	padding: 0 !important;
}
</style>
	<link rel='stylesheet' id='wp-block-library-css'  href='http://localhost/wordpress/wp-includes/css/dist/block-library/style.min.css?ver=5.3.2' type='text/css' media='all' />
</head>
<body>

<script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/wp-embed.min.js?ver=5.3.2'></script>
</body>
</html>

如何添加自己的样式引用呢?

为主题添加脚本和样式的正确方法是将它们添加到 functions.php 文件中。style.css 是所有主题都需要的文件,除此之外,您还可能需要添加其他文件以扩展主题的功能。

将以下代码添加到主题的functions.php中

<?php
/* Add a action to enqueue styles */
function my_theme_enqueue_styles()
{
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>

你可以使用 Filter 过滤钩子或 Action 动作钩子来连接WordPress。 Filter 过滤钩子使你可以更改某些内容(我们将在稍后进行介绍),而 Action 动作钩子使你可以执行某些操作。在我们的例子中,我们需要一些事情(添加样式),因此我们使用 add_action()函数向wp_enqueue_scripts钩子添加一个动作,并注册回调函数my_theme_enqueue_styles(),该回调函数将在从你的主题中收集Css样式或Javascript时执行。

add_action() 函数需要以下4 个参数:

  • $tag:  用于挂载回调函数的动作钩子的名称
  • $function_to_add:  你希望被调用的回调函数的名称
  • $priority:  用于指定执行与特定操作关联的功能的顺序
  • $accepted_args:  回调函数接受的参数数量

请注意,在这种情况下,我们不需要最后两个参数,因此我们不会传递它们,但是稍后我们将介绍它们。

为了避免名称冲突,最好在函数名称前加上主题名称。因此,如果你的主题称为“personal-theme”,则将上述回调函数重命名为“ personal_theme_enqueue_styles ”,并相应地在add_action()函数中更改名称。

引入远程CSS样式文件

<?php
function my_theme_enqueue_styles()
{
  /* 添加一个 purecss framework stylesheet */
  wp_enqueue_style( 'my-theme-purecss', 'https://unpkg.com/[email protected]/build/pure-min.css', array(), '1.0.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>

要添加我们的样式表文件,我们使用了 wp_enqueue_style() 函数,它接受5个参数:

  • $handle:  WordPress中的每个样式表(或脚本)都需要一个唯一的名称,以便您(或一个插件)以后可以引用它。在这里,最好在主题名称前添加前缀。
  • $src:  样式表的URL。这也可以是本地路径,但我们稍后会介绍。
  • $deps:  样式表数组,用于处理该样式表所依赖的样式。
  • $ver:  一个指定样式表版本号的字符串,它将作为查询字符串添加到URL中,以消除浏览器和CDN的缓存。
  • $media:  这个样式表的介质类型。比如 ‘all’, ‘print’ 和 ‘screen’, 或媒体查询,比如 ‘(orientation: portrait)’ 和 ‘(max-width: 640px)’ 。

上面的代码会“排入/添加”新的样式表,而WordPress会将以下链接标记输出到你的网页顶部:

<link rel='stylesheet' id='my-theme-purecss-css' href='https://unpkg.com/[email protected]/build/pure-min.css?ver=1.0.0' type='text/css' media='screen' />

添加条件样式表

PureCss需要两个条件样式表才能使其响应网格起作用。一种样式表用于Internet Explorer 8,一种样式表用于IE8以上的任何浏览器

更改您的functions.php中的代码,并将代码添加到第8至12行。

<?php
function my_theme_enqueue_styles()
{
  wp_enqueue_style( 'my-theme-purecss', 'https://unpkg.com/[email protected]/build/pure-min.css', array(), '1.0.0', 'screen' );
  /* Add conditional framework stylesheets */
  wp_enqueue_style( 'my-theme-purecss-ie8' , 'https://unpkg.com/[email protected]/build/grids-responsive-old-ie-min.css', array() , '1.0.0' , 'screen' );
  wp_style_add_data( 'my-theme-purecss-ie8' , 'conditional' , 'lte IE 8' );
  wp_enqueue_style( 'my-theme-purecss-ie9' , 'https://unpkg.com/[email protected]/build/grids-responsive-min.css', array() , '1.0.0' , 'screen' );
  wp_style_add_data( 'my-theme-purecss-ie9' , 'conditional' , 'gt IE 8' );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>

在这里,我们像之前一样简单地加入了两个样式表,但是紧接着我们通过wp_style_add_data()函数添加了条件。该函数接受三个参数:

  • $handle:  样式表的名称/句柄
  • $key:  我们要为其存储值的数据点的名称。 接受 ‘conditional’, ‘rtl’ , ‘suffix’, ‘alt’ 和 ‘title’
  • $value:  包含要添加的数据的字符串

现在,该代码将在网页顶部加入并输出两个带有条件注释的样式表:

<link rel='stylesheet' id='my-theme-purecss-css'  href='https://unpkg.com/[email protected]/build/pure-min.css?ver=1.0.0' type='text/css' media='screen' />
<!--[if lte IE 8]>
<link rel='stylesheet' id='my-theme-purecss-ie8-css'  href='https://unpkg.com/[email protected]/build/grids-responsive-old-ie-min.css?ver=1.0.0' type='text/css' media='screen' />
<![endif]-->
<!--[if gt IE 8]>
<link rel='stylesheet' id='my-theme-purecss-ie9-css'  href='https://unpkg.com/[email protected]/build/grids-responsive-min.css?ver=1.0.0' type='text/css' media='screen' />
<![endif]-->

引入本地CSS样式文件

要引入本地CSS文件,其实和上面基本一样的操作,只是有一个地方不一样。

<?php
function my_theme_enqueue_styles()
{
 
  /* 添加本地css */
     wp_enqueue_style( 'my-theme-styles', get_template_directory_uri() . '/assets/css/mystyle.css', array(), '1.0.0', 'screen' );

}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>

在这里,你看到的过程是相同的。我们再次使用wp_enqueue_style()函数,但在$src参数中使用get_template_directory_uri()函数。此函数将完整的URL返回到你主题文件夹

引入内联CSS样式

当你需要添加依赖于某些wordpress设置的样式,或者你的样式依赖于其他数据的样式时,可能需要添加内联CSS。

<?php
function my_theme_enqueue_styles()
{
 
  /* 添加内联css样式 */
  wp_register_style( 'my-theme-inline-css', false );
  wp_add_inline_style( 'my-theme-inline-css', '* { color: red; }' );
  wp_enqueue_style( 'my-theme-inline-css' );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>

在这里,我们首先仅使用带有句柄的wp_register_style()注册样式,因此我们可以在入队之前向其添加数据。然后,我们添加要与wp_add_inline_style()函数内联的CSS 。此函数接受两个参数:

  • $handle:  要向其添加其他样式的脚本的名称
  • $data:  包含要添加的Css的字符串

最后,我们再次使用wp_enqueue_style()函数排队样式,仅传递句柄名称。

将Javascript添加到WordPress主题

将Javascript添加到主题的过程与添加样式非常相似,但是有一些细微的区别和额外的选择。

<?php
function my_theme_enqueue_scripts()
{
  /* 添加一个本地 javascript 文件 */
  wp_enqueue_script( 'my-theme-scripts', get_template_directory_uri() . 'https://static.wpdaxue.com/public/js/app.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );
?>

在这里我们没有使用 wp_enqueue_styles()  ,而是使用 wp_enqueue_scripts()  函数,因为我们要引入的是javascript文件。

wp_enqueue_scripts() 函数接受的前4个参数和 wp_enqueue_styles() 一样,但是第5个参数不一样。对于css样式,最后一个参数是 $media ,而javascript 的最后一个参数是 $in_footer ,如果设置为 true,将在页脚加载这个javascript文件。

  • $in_footer:  是否在</body>之前而不是<head> 加载脚本。默认为'false'

现在,代码将进入网页的页脚并在其中输出新的Javascript标记,如下所示:

<script type='text/javascript' src='http://example.com/wp-content/themes/themename/public/js/app.js?ver=1.0.0'></script>

删除一个Javascript文件

在某些情况下,删除一些不必要的脚本会更好一些。例如,大多数WordPress主题都会加入jQuery库。现在,如果你的主题(或插件)不需要它,则从页面上删除它对性能会更好。

假如要删除wordpress自动加载的Js

<script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/wp-embed.min.js?ver=5.3.2'></script>

 可以这样实现:

unction add_theme_scripts() {

    wp_deregister_script('wp-embed');

}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );

 在这里,我们调用wp_deregister_script()函数并传递jquery的句柄。WordPress现在将从页面中删除wb-embed库

其它的详细介绍可以参见:

https://www.wpdaxue.com/how-to-add-css-and-javascript-to-wordpress-theme.html

发布了159 篇原创文章 · 获赞 45 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/lsmxx/article/details/104191950