Add code to head using wp_head action hook
Adding code to the <head>
section of a WordPress site can be useful for a variety of purposes, such as adding custom CSS or JavaScript files, meta tags (<meta>
), or other elements. To add code to the <head>
section of a WordPress site, you can use the wp_head
action hook. Here is an example code snippet:
add_action( 'wp_head', 'wpsnippets_add_code_to_head' );
function wpsnippets_add_code_to_head() {
// Add custom CSS stylesheet file to the head section
wp_enqueue_style( 'custom-style', get_stylesheet_directory_uri() . '/custom-style.css' );
// Add meta tags to the head section
echo '<meta name="description" content="This is a custom meta description">';
echo '<meta name="keywords" content="WordPress, code snippets, head section">';
}
In this code snippet, we define a function wpsnippets_add_code_to_head
that adds a custom CSS file and some meta tags to the <head>
section of the site using the wp_enqueue_style()
function and the echo
statement respectively. Then, we hook this function to the wp_head
action using the add_action()
function.
You can modify this code snippet according to your specific needs, such as adding different CSS or JavaScript files, or other meta tags. Note that you should always use wp_enqueue_style()
or wp_enqueue_script()
functions to enqueue CSS or JavaScript files instead of directly adding them to the <head>
section. This ensures that the files are properly loaded and avoids conflicts with other plugins or themes.
Alternative option: Edit the header.php file directly
Even though this is not always recommended, you can modify the header.php
file of your active theme. The best way to do this, is by using a child theme.
If you don’t know how to make a child theme, you can read about it here in our guide: How to create a WordPress Child Theme (Step by Step)
Here’s an example of how a simple header.php
file might look. You can modify and update this file and add your code within the <head></head>
tags:
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="utf-8">
<meta content="initial-scale=1,width=device-width" name="viewport">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?> id="body"><?php
wp_body_open();
?><main id="main" role="main">
Please note that any edits to theme files will be overwritten when the theme is updated!