Javascript 在 <head> 元素中将 <script> 添加到 WordPress
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5849057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding <script> to WordPress in <head> element
提问by trichnosis
I'm trying to insert this code:
我正在尝试插入此代码:
<script type="text/javascript">
some Javascript codes comes here
</script>
to WordPress' <head></head>
section in front end and in admin panel
到<head></head>
前端和管理面板中的WordPress部分
E.g., Joomla! 1.6 has an API that allows this:
例如,Joomla!1.6 有一个允许这样做的 API:
$doc =& JFactory::getDocument();
$doc->addCustomTag($headTag);
I need to add different things for different pages. For example:
我需要为不同的页面添加不同的东西。例如:
Page 1I need to add
第 1 页我需要添加
<link rel="alternate" type="application/rss+xml" title="feed title" href="feed url" />
For a few pages
几页
Page 2I need to add
第 2 页我需要添加
<script type=\"text/javascript\" src=\"" . LIVE_SITE .
"/wp-content/plugins/jobs/lknlibrary/js/ajax.js\"></script>
<script type=\"text/javascript\">
var ajax = new sack();
var currentClientID=false;
function getClientData()
{
var clientId = document.getElementById('db_country_id').value.replace(/[^0-9]/g,'');
ajax.requestFile = '" .BASE_PATH . "/wp-content/plugins/jobs/com_jobs_admin/tasks/get_location_data.php?task=get_location_data&name=db_parent_id&getClientId='+clientId; // Specifying which file to get
ajax.onCompletion = showClientData; // Specify function that will be executed after file has been found
ajax.runAJAX(); // Execute AJAX function
}
function showClientData()
{
clearJS = ajax.response;
var strTagStrippedText = clearJS.replace(/(<\s*\/?\s*)div(\s*([^>]*)?\s*>)/gi ,'');
document.getElementById('locationsDiv').innerHTML=strTagStrippedText ;
}
function initFormEvents()
{
if (document.getElementById('db_country_id')){
document.getElementById('db_country_id').onchange = getClientData;
document.getElementById('db_country_id').focus();
}
}
window.onload = initFormEvents;
</script>
for a few pages
几页
Page 3I need to add
第 3 页我需要添加
<link rel="stylesheet" type="text/css" href="/wordpress/wp-content/plugins/jobs/lknlibrary/js/tabs/tab.webfx.css" />
for a few pages
几页
I have 70+ pages in admin panel like those above.
我在管理面板中有 70 多个页面,就像上面那样。
Trying to manage the header of the WordPress with the example is a bit difficult.
尝试使用示例管理 WordPress 的标题有点困难。
回答by ggutenberg
In your theme's functions.php
:
在您的主题中functions.php
:
function my_custom_js() {
echo '<script type="text/javascript" src="myscript.js"></script>';
}
// Add hook for admin <head></head>
add_action( 'admin_head', 'my_custom_js' );
// Add hook for front-end <head></head>
add_action( 'wp_head', 'my_custom_js' );
回答by johnmackay61
For anyone else who comes here looking, I'm afraid I'm with @usama sulaimanhere.
对于来这里寻找的其他人,恐怕我和@usama sulaiman 在一起。
Using the enqueue function provides a safe way to load style sheets and scripts according to the script dependencies and is WordPress' recommended method of achieving what the original poster was trying to achieve. Just think of all the plugins trying to load their own copy of jQuery for instance; you better hope they're using enqueue :D.
使用 enqueue 功能提供了一种根据脚本依赖项加载样式表和脚本的安全方法,并且是 WordPress 推荐的实现原始发布者试图实现的目标的方法。例如,想想所有试图加载自己的 jQuery 副本的插件;你最好希望他们正在使用 enqueue :D。
Also, wherever possible create a plugin; as adding custom code to your functions file can be pita if you don't have a back-up and you upgrade your theme and overwrite your functions file in the process.
此外,尽可能创建一个插件;因为如果您没有备份并且升级主题并在此过程中覆盖您的函数文件,则将自定义代码添加到您的函数文件可能会很麻烦。
Having a plugin handle this and other custom functions also means you can switch them off if you think their code is clashing with some other plugin or functionality.
让插件处理这个和其他自定义功能也意味着如果你认为他们的代码与其他插件或功能发生冲突,你可以关闭它们。
Something along the following in a plugin file is what you are looking for:
插件文件中的以下内容是您要查找的内容:
<?php
/*
Plugin Name: Your plugin name
Description: Your description
Version: 1.0
Author: Your name
Author URI:
Plugin URI:
*/
function $yourJS() {
wp_enqueue_script(
'custom_script',
plugins_url( '/js/your-script.js', __FILE__ ),
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', '$yourJS' );
add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet' );
function prefix_add_my_stylesheet() {
wp_register_style( 'prefix-style', plugins_url( '/css/your-stylesheet.css', __FILE__ ) );
wp_enqueue_style( 'prefix-style' );
}
?>
Structure your folders as follows:
按如下方式构建您的文件夹:
Plugin Folder
|_ css folder
|_ js folder
|_ plugin.php ...contains the above code - modified of course ;D
Then zip it up and upload it to your WordPress installation using your add plugins interface, activate it and Bob's your uncle.
然后将其压缩并使用您的添加插件界面将其上传到您的 WordPress 安装,激活它,Bob 就是您的叔叔。
回答by djjeck
Elaborating on the previous answer, you can gather all the required snippets before outputting the header, and only then use an action hook to inject all you need on the head.
详细说明上一个答案,您可以在输出标题之前收集所有必需的片段,然后才使用动作钩子将您需要的所有内容注入头部。
In your functions.php file, add
在您的functions.php 文件中,添加
$inject_required_scripts = array();
/**
* Call this function before calling get_header() to request custom js code to be injected on head.
*
* @param code the javascript code to be injected.
*/
function require_script($code) {
global $inject_required_scripts;
$inject_required_scripts[] = $code; // store code snippet for later injection
}
function inject_required_scripts() {
global $inject_required_scripts;
foreach($inject_required_scripts as $script)
// inject all code snippets, if any
echo '<script type="text/javascript">'.$script.'</script>';
}
add_action('wp_head', 'inject_required_scripts');
And then in your page or template, use it like
然后在您的页面或模板中,像这样使用它
<?php
/* Template Name: coolstuff */
require_script(<<<JS
jQuery(function(){jQuery('div').wrap('<blink/>')});
JS
);
require_script(<<<JS
jQuery(function(){jQuery('p,span,a').html('Internet is cool')});
JS
);
get_header();
[...]
I made it for javascript because it's the most common use, but it can be easily adapted to any tag in the head, and either with inline code or by passing a href/src to an external URL.
我为 javascript 做了它,因为它是最常见的用途,但它可以很容易地适应头部中的任何标签,并且可以使用内联代码或通过将 href/src 传递给外部 URL。
回答by usama sulaiman
I believe that codex.wordpress.org is your best reference to handle this task very well depends on your needs
我相信 codex.wordpress.org 是您处理此任务的最佳参考,这取决于您的需求
check out these two pages on WordPress Codex:
在 WordPress Codex 上查看这两个页面:
回答by Nicola Pedretti
If you are ok using an external plugin to do that you can use Header and Footer Scriptsplugin
如果您可以使用外部插件来执行此操作,则可以使用页眉和页脚脚本插件
From the description:
从描述来看:
Many WordPress Themes do not have any options to insert header and footer scripts in your site or . It helps you to keep yourself from theme lock. But, sometimes it also causes some pain for many. like where should I insert Google Analytics code (or any other web-analytics codes). This plugin is one stop and lightweight solution for that. With this "Header and Footer Script" plugin will be able to inject HTML tags, JS and CSS codes to and easily.
许多 WordPress 主题没有任何选项可以在您的网站或 . 它可以帮助您避免主题锁定。但是,有时它也会给许多人带来一些痛苦。比如我应该在哪里插入 Google Analytics 代码(或任何其他网络分析代码)。这个插件是一站式和轻量级的解决方案。使用这个“页眉和页脚脚本”插件将能够轻松地注入 HTML 标签、JS 和 CSS 代码。
回答by Nicola Pedretti
One way I like to use is Vanilla JavaScript with template literal:
我喜欢使用的一种方式是带有模板文字的 Vanilla JavaScript:
var templateLiteral = [`
<!-- HTML_CODE_COMES_HERE -->
`]
var head = document.querySelector("head");
head.innerHTML = templateLiteral;