0

I need to add a small bit of JavaScript to the <head> section of my site (on every page). I thought Widgets would cover this but I am only able to add widgets to the sidebar and nowhere else.

I've searched around a bit and one solution on Stack Overflow appears to be modifying the functions.php file in my theme. The problem I have with this is that I am using a standard WP theme (Twenty Twelve) so unless I am mistaken, any theme updates would overwrite my changes to the file.

I'm sure I must be missing something simple... I don't really understand why widgets can only go in the sidebar. That's different to every other system I've used.

2
  • In that case, you can rely on this answer. Feb 24, 2014 at 10:59
  • Widgets are designed for output so you'd have to keep in mind that a user could put any widget into any sidebar or widget area. Obviously you wouldn't want someone to put a search bar in the <head> as it would break the site! You can add extra widget areas either via a plugin or a child theme. The typical approach to this problem is to extend a settings page via the settings API or create a theme options page with a textarea for custom area. Many off the shelf themes have something like this. Feb 24, 2014 at 11:34

2 Answers 2

0

I took a closer look at the answer Mayeenul suggested, and with a combination of that and the top answer I got it to work. Seems like a custom plugin is the way to go, and much easier than I expected to implement.

First I created a folder at inside wp-content/plugins/sv-custom-head (using my initials to avoid conflicts) then added one plugins.php file, with this content:

<?php
/*
Plugin Name: SV Custom Head
Description: Description
Version: 1.0
Author:
Author URI:
Plugin URI:
*/

function sv_custom_head()
{
?>
    <script>
    (my code)
    </script>
<?php
}

add_action('wp_head', 'sv_custom_head');
0

Yes, you can do that. My plugin Magic Widgets works this way. It registers a “sidebar” for wp_head, and calls dynamic_sidebar() when this action fires.

I use it to add tracking code or style elements to the output. You just must be careful not to use any regular widget, because they would create invalid HTML. My plugin comes with a custom widget that ignores the normal widget parameters and print just out what you put in in the widget manager page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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