Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

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

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

1 Answer

up vote 1 down vote accepted

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:

     <?php
     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!
share|improve this answer
    
Hey thanks! That's brilliant - works a treat. –  Chris Denman Feb 28 '11 at 12:35
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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