Register Function with wp_head Action Hook in WordPress

WordPress wp_head() 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.

Register Callback Function to wp_head Action Hook

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.

egister callback function with wp_head action hook
register callback function with wp_head action hook

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 Callback Function to wp_head Action Hook

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.