How to: Integrate files on your blog header

When developping a WordPress plugin or widget, you sometimes need to add files as such as CSS or Javascript in the theme header. But how to do it when you can access the theme file? Here’s a simple way to add anything in the blog header without editing header.php.

The principe is simple: You first got top create a function that will simply print the required files. Then, you got to hook it to the wp_head() WordPress function, by using the add_action() function.

function GetLastPostName_head()
{
    echo '<script type="text/javascript" src="'.get_settings('siteurl').'/wp-content/plugins/slidelastposttitle/mootools.js"></script>';
    echo '<script type="text/javascript" src="'.get_settings('siteurl').'/wp-content/plugins/slidelastposttitle/blackbox.js"></script>';
}
add_action('wp_head', 'GetLastPostName_head');

Credits goes to X-OR for this awesome recipe!

7 Responses

Dec 06 2008 11:56

While this is a great recipe, we really should be using wp_enqueue_script() when adding JavaScript.

Dec 06 2008 13:52

@Justin Tadlock: You’re right, wp_enqueue_script() seems more appropriate for adding Javascript. However, the hook is still great for including stylesheets :)

Dec 08 2008 06:19

There’s wp_enqueue_style() for including stylesheets as well.

Stylesheets aren’t as important using this method, but using wp_enqueue_script() is important for adding JS.

Dec 09 2008 03:31

So wp_enqueue_script() would replace what then?

Dec 10 2008 21:09

@WP Cult
It would replace all everything. See the WP Codex article on wp_enqueue_script.

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required