Skip to main content

How to take full advantage of your WordPress sidebar

Published ago
Updated ago
27 min read
Warning

This article was written in 2010 👴🏼. Most of the tips here are not valid anymore and I don't recommend using any of the snippets displayed here.

I'm keeping this article here for historical reasons and to remind myself how much I've improved over the years.

Only cosmetic changes were made to this article.

I am going to show you some codes and hacks that can be applied to almost any theme you want, this will add some really cool features to your sidebar and who knows, it may even get you on a date tonight.

Truth be told, in my early years in WordPress and theme designing, I never thought the sidebar was something useful, in fact, my first theme didn't even had one at all, but time later, I realized how much in-screen space I was wasting, and changed my mind. This is a walkthrough for the re-design of the WordPress former default theme Kubrik's sidebar, prior to this; I added the sidebar to single posts, just in case you are wondering where it came from.

Creating different sidebars

First of all, we are going to need two sidebar files, name the first one sidebar.php so it works on pages too (this is the default one), then we create a new one which will be shown in our single posts, let's call this one sidebar-single.php

Note

In sidebar-single.php I deleted almost everything, except for the search box and some text.

Separate Home sidebar from Single sidebar

Now, we need WordPress to separate our “home sidebar” from our “single-post sidebar”, this is easier if your theme has a single.php file like here, but if not, I strongly recommend you create one now, it will save you a lot of troubles in the future.

To make wordpress show a different sidebar in single posts you just have to open the single.php file, find the call to the sidebar and tell it to call the new sidebar instead, something like this:

Now in our blog we can see this:

Home:

Single Post:

What if I don't want a single.php file?

I guess we have a rebel here. Well, if you really don't want a single.php file messing around in your theme you can just use the index.php file, to do that just find the line where the sidebar is called:

1<?php get_sidebar(); ?>
2

And change it for this:

1<?php
2 if( is_single() ) {
3 get_sidebar( 'single' );
4 } else {
5 get_sidebar();
6 }
7?>
8

That code will show our single-sidebar ONLY if we are on a single post. If not, it will show our default sidebar.

OK, now we have a sidebar just for our single posts, how can we use it? There are plenty of ways! For example, do you show related posts or social icons below your posts? Maybe some of this stuff can look better on our new sidebar, let's try it.

Let's start by adding some related entries to our post, to do that I am using the YARPP plug-in (an old version, don't judge me!), in your sidebar-single.php add the related_posts() function (or whatever function your plug-in uses) and now in your blog you should see something like this:

There is another way to display related posts without needing a plug-in, but I just cannot make it work on the sidebar, still, I don't see any problem in using a plug-in for this (since it is the only plug-in I am using in this tutorial).

Adding Social Media buttons

Looks good! Now let's add some social media buttons like Twitter or Facebook, I am using this set of social icons.

Here in the default theme I don't have much space, so I will just add twitter and facebook buttons, but if you want to add more, it's pretty much the same thing.

Adding a Facebook button is easy because you only need to share the URL, you just have to paste the following code to the sidebar.

1<a href="http://www.facebook.com/sharer.php?u=<?php the_permalink(); ?>" target="_blank"><img src="<?php bloginfo('template_directory'); ?>/images/facebook.png" alt="Share on Facebook" /></a>
2

Twitter, on the other hand, is a little tricky because you want to let your followers know what are you sharing, so you have to add the title, then, when you only have 140 characters to use, you cannot send the full URL along with the title, therefore, you need a short URL.

There are plenty of services to shorten an URL, and you can even create your own, but right now you can use services like tinyurl or bit.ly if you want.

Adding “+” to the title

I've found that sometimes in Twitter, if you don't add a plus sign “+” to the title when sending a tweet from a link, it shows a horrible “%20” on every space, luckily, there is a simple way to fix this.

This goes into your functions.php file (noticed the importance of this file already?)

1<?php
2 function twitle( $title ) {
3 $newtitle = str_replace( " ", "+", $title );
4 echo $newtitle;
5 }
6?>
7

You don't really need to create a function just for that, but I think it could be useful later on.

Using Tinyurl

If you want to use tinyurl here is the code you need, paste it on your functions.php file:

1function tinyurl( $url ) {
2 $tinyurl = file_get_contents( "http://tinyurl.com/api-create.php?url=" . $url );
3 return $tinyurl;
4}
5

Now, paste the following code in your sidebar:

1<a href="http://twitter.com/home?status=<?php twitle( the_title() ); ?>+<?php echo tinyurl( get_permalink() ); ?>" target="_blank"><img src="<?php bloginfo('template_directory'); ?>/images/twitter.png" alt="Share on Twitter" /></a>
2
Note

I have not tried this, but according to WPRecipes2 it works (I just made a few changes).

Using bit.ly

I prefer bit.ly because it lets you keep a track of your shortened URLs, and it is shorter than tinyurl.

First you need to sign up in bit.ly, and then you will have access to an API key, again, paste this code into your functions.php file:

1//create bit.ly url
2function bitly() {
3 // login information
4 $url = get_permalink(); //generates wordpress' permalink
5 $login = '';//your bit.ly login
6 $apikey = ''; //your bit.ly apikey
7 $format = 'json';//choose between json or xml
8 $version = '2.0.1';
9 //create the URL
10 $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;
11 //get the url
12 //could also use cURL here
13 $response = file_get_contents($bitly);
14 //parse depending on desired format
15 if(strtolower($format) == 'json')
16 {
17 $json = @json_decode($response,true);
18 echo $json['results'][$url]['shortUrl'];
19 }
20 else //xml
21 {
22 $xml = simplexml_load_string($response);
23 echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
24 }
25}
26

Don't forget to fill with your username and API key, after that paste this in your sidebar:

1<?php $bitlyurl = bitly(); ?>
2<a href="http://www.twitter.com/home?status=<?php twitle(the_title('','',false)); ?>+<?php echo $bitlyurl; ?>" target="_blank"><img src="<?php bloginfo('template_url'); ?>/images/twitter.png" alt="Tweet me!" /></a>
3
Warning

I have not tried this either, source: DevMoose

Using your own domain

I believe that using your own domain is the best way to create a short URL, it gives you presence, personality and your potential readers know that they are going to a serious website (yes, that's right). Still, if you have a long domain (like thisisthebestblogeveraccordingtomymomlol.com) maybe you should use bit.ly or tinyurl.

The easiest way to create a short URL in wordpress is to use “the Post ID”, just paste this in your sidebar:

1<a href="http://www.twitter.com/home?status=<?php twitle(the_title('','',false)); ?>+<?php bloginfo('url') ?>/?p=<?php echo $post->ID; ?>" rel="nofollow" target="_blank"><img src="<?php bloginfo('template_url'); ?>/images/twitter.png" alt="Tweet me!"/></a>
2

That will send twitter something like this: Hello World http://domain.com/?p=123, it's short, but it can be even shorter. In addition, you can change <?php get_bloginfo('url') ?> (which sends your blog URL) for another domain if you like, for example, a hack domain like aweso.me or bite.me (you know, something cool), just remember that you have to own that domain (don't even think about youtu.be).

Using your own domain v2.0

Using the previous code, and adding some 301 redirection to our .htaccess file we can get rid of the ?p= earning three precious characters.

In the previous code, delete ?p= so it becomes:

1<a href="http://www.twitter.com/home?status=<?php twitle(the_title('','',false)); ?>+<?php bloginfo('url') ?>/<?php echo $post->ID; ?>" rel="nofollow" target="_blank"><img src="<?php bloginfo('template_url'); ?>/images/twitter.png" alt="Tweet me!"/></a>
2

That sends something like this Hello World http://domain.com/123, but it also comes with a pretty 404 error. In order to fix that we have to add this rule to our .htaccess file:

1#shorturl
2RewriteRule ^([0-9]+)$ ?p=$1 [R=301,L]
3#shorturl
4

There! Now our own short URL is working, and now our sidebar looks something like this (with working buttons yay!):

Adding a “Share me!” URL

You also may want to add a short URL so your readers can share the post by themselves, if so, just add the following code depending the shortening method you chose before:

Tinyurl

1<form>
2<input id="shorturl" name="q" size="30" readonly="readonly" onClick="javascript:this.form.shorturl.focus();this.form.shorturl.select();" value="<?php echo $turl; ?>" type="text">
3</form>
4

Bit.ly

1<form>
2<input id="shorturl" name="q" size="30" readonly="readonly" onClick="javascript:this.form.shorturl.focus();this.form.shorturl.select();" value="<?php echo $bitlyurl; ?>" type="text">
3</form>
4

Your own domain v1.0

1<form>
2<input id="shorturl" name="q" size="30" readonly="readonly" onClick="javascript:this.form.shorturl.focus();this.form.shorturl.select();" value="<?php bloginfo('url'); ?>/?p=<?php echo $post->ID; ?>" type="text">
3</form>
4

Your own domain v2.0

1<form>
2<input id="shorturl" name="q" size="30" readonly="readonly" onClick="javascript:this.form.shorturl.focus();this.form.shorturl.select();" value="<?php bloginfo('url'); ?>/<?php echo $post->ID; ?>" type="text">
3</form>
4

That will show something like this:

Caution

You MUST use the same shortening method you used before if you want this to work.

Now let's add some more posts in the same category as the one we are reading (we want the reader to stay in our blog for a while don't we?)

I took this function (well, it wasn't a function when I took it) from the Agregado theme (which by the way, really knows how to take advantage of the sidebar), add the first code in your functions.php file, and the second one in your sidebar-single.php file.

1<?php
2function get_more_category() {
3global $post;$categories = get_the_category();foreach ($categories as $category) :$posts = get_posts('numberposts=3&exclude='.$post->ID.'&category='. $category->term_id);if(count($posts) > 1) {?><h2>More <em>in</em> '<?php echo $category->name; ?>':</h2><p><ul><?php foreach($posts as $post) : ?><li><a href="<?php the_permalink(); ?>"<?php the_title(); ?></a></li><?php endforeach; ?></ul></p><?php } endforeach;}<?php get_more_category(); ?>
4

Showing author info

If you have a blog with more than one author you may want to add a small bio to each post right? All the others blog do it by showing the info below the post but since we like to be different, and we are improving our sidebar, how about putting the bio in there? Be sure to fill completely your profile page on the WP admin, that is what we are going to use.

Once you have done that, paste this in your sidebar:

1<?php the_author_link(); ?> is a <?php the_author_meta('description'); ?>
2

Assuming that I have already put my info on my profile page, this would show something like this:

Mario is a cool designer who loves making themes, writing blogs and eating babies, in that order.

Note: If you want to add a gravatar, use this:

1<?php echo get_avatar( get_the_author_meta('user_email'), '80', '' ); ?>
2

Where “80” is the size (in pixels) of the image, you can change that too. Source.

Note

Starting here, the next tricks will fit better on our home sidebar (the sidebar.php file).

In case you want to add a list with your blog's most popular posts (well, actually most commented), you are in the right place.

This goes in your functions.php file:

1function most_popular_posts($no_posts = 10, $before = '<li>', $after = '</li>', $show_pass_post = false, $duration='') {
2global $wpdb;
3$request = "SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS 'comment_count' FROM $wpdb->posts, $wpdb->comments";
4$request .= " WHERE comment_approved = '1' AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status = 'publish'";
5if(!$show_pass_post) $request .= " AND post_password =''";
6if($duration !="") {
7$request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";
8}
9$request .= " GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts";
10$posts = $wpdb->get_results($request);
11$output = '';
12if ($posts) {
13foreach ($posts as $post) {
14$post_title = stripslashes($post->post_title);
15$comment_count = $post->comment_count;
16$permalink = get_permalink($post->ID);
17$output .= $before . '<a href="' . $permalink . '" title="' . $post_title.'">' . $post_title . '</a> (' . $comment_count.')' . $after;
18}
19} else {
20$output .= $before . "None found" . $after;
21}
22echo $output;
23}
24

And this goes in your sidebar:

1<h2>Popular</h2>
2<ul><?php most_popular_posts(); ?></ul>
3

Showing recent posts

Many blogs (almost all of them) show some recent posts in their home, and there are many plug-ins for that, but I said I wouldn't use more plugins, and I cannot take that back right?

I took this code from the well known Recent Posts plug-in, it's just one function, so it can easily be placed in our functions.php file.

1<?php function mdv_recent_posts($no_posts = 5, $before = '<li>', $after = '</li>', $hide_pass_post = true, $skip_posts = 0, $show_excerpts = false, $include_pages = false) {
2global $wpdb;
3$time_difference = get_settings('gmt_offset');
4$now = gmdate("Y-m-d H:i:s",time());
5$request = "SELECT ID, post_title, post_excerpt FROM $wpdb->posts WHERE post_status = 'publish' ";
6if($hide_pass_post) $request .= "AND post_password ='' ";
7if($include_pages) $request .= "AND (post_type='post' OR post_type='page') ";
8else $request .= "AND post_type='post' ";
9$request .= "AND post_date_gmt < '$now' ORDER BY post_date DESC LIMIT $skip_posts, $no_posts";
10$posts = $wpdb->get_results($request);
11$output = '';
12if($posts) {
13foreach ($posts as $post) {
14$post_title = stripslashes($post->post_title);
15$permalink = get_permalink($post->ID);
16$output .= $before . '<a href="' . $permalink . '" rel="bookmark" title="Permanent Link: ' . htmlspecialchars($post_title, ENT_COMPAT) . '">' . htmlspecialchars($post_title) . '</a>';
17if($show_excerpts) {
18$post_excerpt = stripslashes($post->post_excerpt);
19$output.= '<br />' . $post_excerpt;
20}
21$output .= $after;
22}
23} else {
24$output .= $before . "Can't find any :S" . $after;
25}
26echo $output;
27}
28?>
29

Paste this in your sidebar:

1<?php mdv_recent_posts(); ?>
2

Showing recent comments

Blogs are all about the community, so we want our readers to make a lot of comments, but they are shy, they need to know that some other cool guy did it before. To make this happen, we need to show a list with the most recent comments on our blog.

Paste the following code to your functions.php file (sorry, but I really cannot remember where I took this from, it was on my functions.php file):

1<?php
2function recent_comments($comm = 5) {
3global $wpdb;
4$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,comment_author_url, SUBSTRING(comment_content,1,30) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT $comm";
5$comments = $wpdb->get_results($sql);
6$output = $pre_HTML;
7$output .= "n<ul class="recentcomments">";
8foreach ($comments as $comment) {
9$output .= "n<li><strong>".strip_tags($comment->comment_author) ."</strong> <em>on</em> " . "<a href="" . get_permalink($comment->ID)."#comment-" . $comment->comment_ID . "" title="". strip_tags($comment->com_excerpt). "">".$comment->post_title ."</a></li>";
10}
11$output .= "n</ul>";
12$output .= $post_HTML;
13echo $output;
14}
15

Now we call the function from our sidebar:

1<?php recent_comments(); ?>
2

Showing random posts

At this point, we have a lot of posts showing in our sidebar, but that is a good thing right? Posts! Posts everywhere!!

Ok, just add the following code to your sidebar:

1<li><h2>Random posts</h2></li>
2<li><ul>
3<?php
4$rand_posts = get_posts('numberposts=5&orderby=rand');
5foreach( $rand_posts as $post ) :
6?>
7<li><a href="<?php the_permalink(); ?>">
8 <?php the_title(); ?>
9</a></li>
10<?php endforeach;
11?>
12</ul></li>
13

Source

Displaying a Blogroll

OK, maybe this is not the ultimate-wordpress-trick, but it is pretty useful when you have several websites, or you can show all your profiles on twitter, facebook, linkedin, etc. Just add those links in your wordpress link manager, and show them with this code:

1<?php wp_list_bookmarks('title_li=&category_before=&category_after='); ?>
2

The result

I think now we have a pretty useful sidebar for our blog, but if you want, you can keep adding features as you like, there is no limit!

Here is how my sidebar looks like after a few little fixes:

Be creative!

Remember, this is just an example, your sidebar doesn't have to look exactly like mine, but I hope that these tips/tricks help you to take full advantage of your sidebar, also, be creative! Think of different ways to use that sidebar, I saw this blog once that had the comments in the sidebar. Put yourself in your reader's place, how can their experience be improved?