Skip to content

Instantly share code, notes, and snippets.

@endurtech
Last active January 16, 2023 07:04
Show Gist options
  • Save endurtech/1ff16d388c8ad2548f207fad7726aad7 to your computer and use it in GitHub Desktop.
Save endurtech/1ff16d388c8ad2548f207fad7726aad7 to your computer and use it in GitHub Desktop.
Insert this code into the functions.php file within your WordPress child-theme to inject any custom code into the HEADER area of a specific page on your WordPress website.
<?php
// Inserting Header Script on Specific Page with WordPress
// https://endurtech.com/insert-script-into-wordpress-header/
add_action( 'wp_head', 'custom_header_page_scripts', 2 );
function custom_header_page_scripts()
{
if( is_page( 123 ) ) //set page number to your page number
{
echo '<script>alert( "This script is triggered within the header of page-id 123 on your website." );</script>';
}
}
// Alternatively, you can stop and restart PHP processing to inject your code
// which helps bypass potential issues with apostrophes or quotations
add_action( 'wp_head', 'custom_header_page_scripts', 2 );
function custom_header_page_scripts()
{
if( is_page( 197 ) ) // change the target page number (197) to your desired target page number
{
?>
<script>alert( "This script is triggered from within the header of page-id 123 on your website." );</script>
<?php
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment