动态添加 meta 标签
There are times where you may want to conditionally inject stylesheets or scripts into your header or footer, or you'd simply prefer to inject those resources via PHP instead of place the HTML in template files directly. WordPress' ever-powerful add_filter
function provides the a method for injecting stylesheets or scripts into the header, as well as scripts into the footer. Here's how!
有时您可能希望有条件地将样式表或脚本注入到页眉或页脚中,或者您只希望通过PHP注入这些资源,而不是将HTML直接放置在模板文件中。 WordPress强大的add_filter
函数提供了一种将样式表或脚本注入页眉以及将脚本注入页脚的方法。 这是如何做!
// Add items to the header!
function shimify() {
echo '<!--[if lt IE 9]><script src="/wp-content/themes/mytheme/shim.js"></script><![endif]-->';
echo '<style>/* some styles here */</style>';
echo '<meta http-equiv="content-type" content="text/html;" />';
}
add_filter('wp_head', 'shimify');
// Add items to the footer
function add_requirejs() {
echo '<script src="/wp-content/themes/mytheme/requirejs.js"></script>';
}
add_filter('wp_footer', 'add_requirejs');
The add_filter
function, which accepts the filter type, action function, and optional priority, provides the means to inject stylesheets and JavaScript files wherever desired. You may want to conditionally inject a different Google Analytics account if you use a WordPress install that loads different content depending on hostname. Do not use this technique if you're adding stylesheets or scripts for your plugin -- those should be added with the proper WordPress functions!
add_filter
函数接受过滤器类型,操作函数和可选的优先级,它提供了在需要时注入样式表和JavaScript文件的方法。 如果您使用根据主机名加载不同内容的WordPress安装,则可能需要有条件地注入其他Google Analytics(分析)帐户。 如果您要添加的插件样式表或脚本, 不要使用这种技术-这些应与被添加适当的WordPress的功能 !
动态添加 meta 标签