Last updated on May 25, 2023
WordPress allows you to add and remove any action into the header. To add any action in the header you can use add_action() function that takes information of the action that need to be added.
WordPress wp_head() function uses the head section to add meta tags, CSS files, and scripts based on provided priority. It calls all the functions registered with the wp_head hook. Mostly it uses in plugin and theme development.
Usually, the wp_head() function is called in the header.php file of the WordPress theme where developers add the necessary code inside the head section of the website.
In this article, we will learn to add HTML tags into the head section through wp_head() action hook. Let’s add a meta description tag that helps search engines for fetching the page’s description.
So go to the activated theme’s folder and open functions.php.
function metaDescription() {
echo '<meta name="description" content="Add description of page" />';
}
Next, copy and paste the above function that simply returns the meta tag with its attributes. Now we need to register it with the wp_head() hook. For that WordPress’s add_action() function will help us.
So under the metaDescription() function add_action() function same as below,
add_action('wp_head', 'metaDescription');
It will register the newly created function with the wp_head action hook which will render the description meta tag into the head element in HTML.
add_action() function has two required parameters, the first is the hook name and the second is the callback or function name that needs to register.
It has also two optional parameters which are the priority and accepted arguments.
add_action('wp_head', 'metaDescription', 1);
In the above script, the third argument is a priority that sets priority when the hook calls registered functions. A lower number or value means the function will be run at the start and a similarly higher number will run the function at the end.
remove_action() function removes registered callback function from action hook. For example to remove metaDescription function from wp_head action hook we need to add remove_action() function into functions.php.
remove_action( 'wp_head', 'metaDescription' );
The above function will simply remove the callback function from the wp_head action hook.
This article demonstrates how can a function can be registered in the wp_head action hook. To register a function into wp_head action hook, you need to use the add_action() function that accepts four parameters in which 2 are required. The first parameter is the hook name and the second is the function that needs to be registered.