Add after body hook hack in wordpress (e.g. for Facebook Like button SDK) without modifying header.php

I wish to add the Facebook Like button to my wordpress – this requires that I add the following code right after <body<:
<div id="fb-root"></div><script>(function(d, s, id) {
...
}(document, 'script', 'facebook-jssdk'));</script>

My solution
Make a functions.php file in your child theme and add the following code (or append it to your main functions.php if you are silly enough to not use child themes). It abuses the body_class hook by finishing the <body< tag and then prints the actual content:
add_action('body_class','hook_after_body');

function hook_after_body()
{?>
<div id="fb-root"></div><script>(function(d, s, id) {
<script>(function(d, s, id) {
...
}(document, 'script', 'facebook-jssdk'));</script
<?}

Solutions that I don’t like

  • I could just override header.php in my (child)theme, but then my modifications will be lost, if I update my wordpress theme. Plus it makes it harder for me to know what code that I have changed.
  • I could also just use a plugin to get extra hooks, but I hate to install extra plugins because they makes me depend code from more on other people and the plugins can also be a security risk.


Fernando pointed out that this generates invalid HTML. While there are some ways of adding content after the body (http://wordpress.stackexchange.com/questions/73370/how-to-inject-content-after-body), I have decided to just use override header.php in my child theme – I had to do that anyway.

2 thoughts on “Add after body hook hack in wordpress (e.g. for Facebook Like button SDK) without modifying header.php

  1. Esto no funciona, lo probé y lo que hace es mostrar el código de facebook justo antes de la class del body, lo cual daña el código html del blog.

    Yo utilicé algo que encontré en http://wordpress.stackexchange.com/questions/73370/how-to-inject-content-after-body

    En mi caso decidí utilizar lo que había en el ultimo comentario y funciono bien.
    add_action(‘shutdown’, function() {
    $final = ”;
    $levels = ob_get_level();
    for ($i = 0; $i < $levels; $i++){
    $final .= ob_get_clean();
    }
    echo apply_filters('final_output', $final);
    }, 0);

    add_filter('final_output', function($output) {
    $after_body = apply_filters('after_body','');
    $output = preg_replace("/(\)/”, “$1”.$after_body, $output);
    return $output;
    });

    add_action(‘after_body’,function($after_body){
    $after_body.=’My Content’;
    return $after_body;
    });

    En este caso solamente habría que cambiar My Content por lo que sea que quieras mostrar después del elemento

    si el código no se ve bien revisa el enlace.

Leave a Reply

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