简体   繁体   English

在<head>元素中将<script>添加到WordPress

[英]Adding <script> to WordPress in <head> element

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 到前端和管理面板中的WordPress' <head></head>部分

Eg, Joomla! 好吧,Joomla! 1.6 has an API that allows this: 1.6有一个允许这样的API:

        $doc =& JFactory::getDocument();
        $doc->addCustomTag($headTag);

I need to add different things for different pages. 我需要为不同的页面添加不同的东西。 For example: 例如:

Page 1 I need to add 第1页我需要添加

<link rel="alternate" type="application/rss+xml" title="feed title" href="feed url" />

For a few pages 几页

Page 2 I 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 3 I 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的标题有点困难。

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' );

For anyone else who comes here looking, I'm afraid I'm with @usama sulaiman here. 对于任何来这里看的人,我恐怕我和@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. 使用enqueue函数提供了一种根据脚本依赖性加载样式表和脚本的安全方法,并且是WordPress推荐的实现原始海报试图实现的方法。 Just think of all the plugins trying to load their own copy of jQuery for instance; 想想所有试图加载自己的jQuery副本的插件; you better hope they're using enqueue :D. 你最好希望他们使用入队: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是您的叔叔。

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。

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上查看这两页:

wp_enqueue_script wp_enqueue_script

wp_enqueue_style wp_enqueue_style

If you are ok using an external plugin to do that you can use Header and Footer Scripts plugin 如果您可以使用外部插件来执行此操作,则可以使用页眉和页脚脚本插件

From the description: 从描述:

Many WordPress Themes do not have any options to insert header and footer scripts in your site or . 许多WordPress主题没有任何选项可以在您的网站中插入页眉和页脚脚本。 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). 我应该在哪里插入Google Analytics代码(或任何其他网络分析代码)。 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. 使用这个“页眉和页脚脚本”插件将能够轻松地注入HTML标签,JS和CSS代码。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM