I have some custom code that sits inside <head></head>. When I install a new WordPress theme I have to edit the header.php script each time.

Is there a way to always include my custom code inside the head tags even when installing a new WordPress theme?

migrated from stackoverflow.com Feb 28 '11 at 1:00

This question came from our site for professional and enthusiast programmers.


You want to create a new plugin for this. See: http://codex.wordpress.org/Plugin_API/Action_Reference/wp_head

  1. Create a new file in /wp-content/plugins/ called headerstuff.php (or whatever)
  2. Drop the following code in it:

     function header_code() {
     $output .= ""; //code segment 
     echo $output;
     add_action('wp_head', 'header_code');
  3. Add your code between the quotation marks on the line starting with "$output".

  4. Activate, done!
  • I am starting to really find my way around now, however I spent maybe 4 hours last night trying to work out the following: I want to now insert some html before any search results - someone does a search (may or may not get results) and I want above the results (be it posts or snippets) my chunk of code. I actually got it working by using add_filter('the_content', 'myresults'); add_filter('the_posts', 'myposts'); However didn't realise that some themes don't show a post - just a list of links to posts. Any ideas? My site is foundfor.me - this theme my technique works. – Chris Denman Feb 28 '11 at 12:36
  • There's no easy way to do this presently -- see: wordpress.org/support/topic/add_action-right-after-ltbodygt-tag. That forum post has two useful bits of code: a jQuery snippet to insert code just after <body>, and a link to a trac patch inserting a new action called body_open. That said, the latter requires a new line of code in every theme you use it in, so its utility is somewhat questionable. – aendrew Feb 28 '11 at 18:10
  • Thanks for the heads up - that have saved me many hours looking for something that doesn't exist! – Chris Denman Feb 28 '11 at 22:06
  • No problem. It's really unfortunate that they didn't think to include such a hook, would probably be useful for AJAXy things. I get why it's not really that possible now, though; see the trac. Btw, if I've sufficiently answered your question, mind accepting my answer? Thanks! – aendrew Mar 2 '11 at 4:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.