[javascript] 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

E.g., Joomla! 1.6 has an API that allows this:

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

I need to add different things for different pages. For example:

Page 1 I need to add

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

For a few pages

Page 2 I need to add

<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

 <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.

Trying to manage the header of the WordPress with the example is a bit difficult.

This question is related to javascript wordpress plugins

The answer is


One way I like to use is Vanilla JavaScript with template literal:

var templateLiteral = [`
    <!-- HTML_CODE_COMES_HERE -->
`]

var head = document.querySelector("head");
head.innerHTML = templateLiteral;

For anyone else who comes here looking, I'm afraid I'm with @usama sulaiman here.

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.

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.


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

$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.


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 . 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.


In your theme's 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' );

I believe that codex.wordpress.org is your best reference to handle this task very well depends on your needs

check out these two pages on WordPress Codex:

wp_enqueue_script

wp_enqueue_style


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to wordpress

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’ How to get WooCommerce order details Wordpress plugin install: Could not create directory WooCommerce: Finding the products in database How to get post slug from post in WordPress? How to get featured image of a product in woocommerce Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610 Use .htaccess to redirect HTTP to HTTPs Load More Posts Ajax Button in WordPress How to decode encrypted wordpress admin password?

Examples related to plugins

How to view Plugin Manager in Notepad++ How to install a Notepad++ plugin offline? "Gradle Version 2.10 is required." Error How to download PDF automatically using js? How to: Install Plugin in Android Studio "application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint How can I call a WordPress shortcode within a template? How can I simulate mobile devices and debug in Firefox Browser? How to install plugins to Sublime Text 2 editor? How to add java plugin for Firefox on Linux?