Using WordPress ‘wp_head’ PHP action

The wp_head WordPress PHP action hook allows you to add scripts, styles, or meta information to the <head> section of a WordPress theme.

Usage

add_action('wp_head', 'my_custom_head_code');
function my_custom_head_code() {
// your custom code here
}

Parameters

  • No parameters.

More information

See WordPress Developer Resources: wp_head

Keep in mind that this hook is theme-dependent, but it is widely supported across various themes. Remember to use proper priority if you need to remove a default hook.

Examples

Adding a custom stylesheet

This example adds a custom stylesheet to the <head> section of the theme.

add_action('wp_head', 'add_custom_stylesheet');
function add_custom_stylesheet() {
    echo '<link rel="stylesheet" href="' . get_stylesheet_directory_uri() . '/custom.css" />';
}

Adding custom meta tags

This example adds custom meta tags for SEO purposes.

add_action('wp_head', 'add_custom_meta_tags');
function add_custom_meta_tags() {
    echo '<meta name="description" content="A custom description for my site">';
    echo '<meta name="keywords" content="custom,keywords,for,my,site">';
}

Adding a favicon

This example adds a favicon to the <head> section of the theme.

add_action('wp_head', 'add_favicon');
function add_favicon() {
    echo '<link rel="shortcut icon" href="' . get_stylesheet_directory_uri() . '/favicon.ico" />';
}

Adding a custom JavaScript file

This example adds a custom JavaScript file to the <head> section of the theme.

add_action('wp_head', 'add_custom_js');
function add_custom_js() {
    echo '<script src="' . get_stylesheet_directory_uri() . '/custom.js"></script>';
}

Adding Google Analytics

This example adds Google Analytics tracking code to the <head> section of the theme.

add_action('wp_head', 'add_google_analytics');
function add_google_analytics() {
echo "<script async src='https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X'></script>";
echo "<script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXXX-X');
</script>";
}