Hack: Adding Lines To Your Page Head Without Altering Your Theme

Typically when someone wants to add a bunch of stuff to the <head> tag of a theme, they edit the header.php file in the theme or child theme. But even doing it properly in the child theme means that file overrides the header.php of the parent theme and won’t get updates from that point on.

A better way to add things is to use the wp_head hook. You can insert what you like without even needing a child theme. Here’s an example

add_action('wp_head', 'wpaction_add_something', 1);
function wpaction_ wpaction_add_something() {
	if (is_single()) {
		echo("<script></script>\n");
	}
}

In this example I even qualify the addition with is_single so it only appears on post pages. But I could use anything to qualify it, even adding things only on specific pages, posts, or with tags and such. This would work in the functions.php or in a custom plugin. The number in the third parameter determines where in the head the insertion will appear. So 1 is early while 10 is at the end.

Leave a Reply

Your email address will not be published. Required fields are marked *