skip to Main Content

Add custom JavaScript to the WordPress Header with functions.php

To add a tiny simple JavaScript, for instance  a test for some jQuery functionality, to your WordPress head in the frontend simply add this to your themes functinos.php. Be aware that the jQuery included with WordPress runs in NoConflict Mode, meaning that there is no $, but instead jQuery.

function my_header_script(){ ?> <script>alert( 'This is a header test' ); </script> <?php}add_action( 'wp_head', 'my_header_script' );

You can also add something to the footer

function my_footer_script(){ ?> <script>alert( 'This is a footer test' ); </script> <?php}add_action( 'wp_footer', 'my_footer_script' );

Or via

add_action( 'wp_footer', function() { ?>	<script>		( function( $ ) {			'use strict';			$( document ).ready( function() {				// change "open-vc-row-pricing" to be the class used in the module you want to click to open the hidden row				var $trigger = $( '.open-vc-row-pricing' );				// change "vc-row-pricing" to be the class used in the hidden row				var $hiddenRow = $( '.vc-row-pricing' );				if ( $hiddenRow.length ) {					$ function() {						$hiddenRow.toggle();						return false;					} );				}			} );		} ( jQuery ) );	</script><?php }, 99 );

If you want to add something to the backend use this:

// Add inline CSS in the admin head with the style tagfunction my_custom_admin_head() {	echo '<style>[for="wp_welcome_panel-hide"] {display: none !important;}</style>';}add_action( 'admin_head', 'my_custom_admin_head' );// Add inline JS in the admin head with the <script> tagfunction my_custom_admin_head() {	echo '<script type=""text/javascript">console.log('admin script')</script>';}add_action( 'admin_head', 'my_custom_admin_head' );

Another example that makes it easier to format the code:

function my_custom_admin_head() {echo '<script type="text/javascript">';echo 'jQuery(document).ready(function(){alert("Hello"); });//alert("Hello");'; echo '</script>';}add_action( 'admin_head', 'my_custom_admin_head' );


Read more:


Back To Top