Hooking a function onto the sidebar?

I’m looking for a way to add some content to the top of the sidebar when it get’s loaded.

I’ve tried hooking onto the get_sidebar action as referenced here, but it seems to override the sidebar call and load my function instead? Is there a better solution to doing this beside creating widgets? I’d like to avoid that if possible, but I’m not totally against the idea, a hook would be best 🙂

Here’s what my hook looks like:
add_action('get_sidebar', 'social_links');

Note: the function called is just spitting a list of social media links, nothing too fancy…

(Running latest version (3.1) on a MAMP server locally)

Solutions Collecting From Web of "Hooking a function onto the sidebar?"

Load at the sidebar bottom

In most of the sidebars, you’ll find the call to the wp_meta() action hook, where you can hook into the (mostly bottom) of a sidebar.

Load on top of your sidebar

The function get_sidebar( $name ) calls the sidebar you want in your template (this allows to have different sidebars). If you want to add stuff to eg. the top of your sidebar, you’re free to use the internal action hook that runs top of your sidebar, right before the sidebar gets loaded You can then hook everything into this call.


function add_before_my_siderbar( $name ) 
    echo "Loaded on top of the {$name}-sidebar";

    // Example that uses the $name of the sidebar as switch/trigger
    'main' === $name AND print "I'm picky and only echo for special sidebars!";
add_action( 'get_sidebar', 'add_before_my_siderbar' );

Notes about themes

The get_sidebar-hook is on top of the get_sidebar() function and triggers before the sidebar file gets included. This means, you should use this hook to add content before and wp_meta() to add something after the sidebar. If a theme is using wp_meta() earlier than the end of sidebar template, then it’s doing it wrong.

get_sidebar hook is called on the function that gets the sidebar template file so that’s not the right way to go.

if you are not up to creating a widget you can convert your function to a shortcode and use it in the built-in text widget.

How? simple, you say your function is named social_links then add:

add_shortcode('SL', 'social_links'); 
// and to make sure WordPress calls shortcode in sidebars
add_filter('widget_text', 'do_shortcode');

Usage? once again simple, add a text widget and put [SL] in it.

Just make sure that your function returns the output instead of echoing it.

Instead of return on the wp_metahook, echo the result example:


function my_function(){
   //no return 'hello';
   //try this and it will shows at the top of the sidebar
   echo 'hello';

See: wp_meta hook on Codex