Multiple loops, post formats, and content types in a single home page template

Wow. That title is a mouthful. And given the improbable combination of different content types, I’m actually somewhat surprised that I did, in fact, pull off just that. In working on a client site for a Christian ministry in the Democratic Republic of Ghana, I set out today to create this:

ibm homepage Multiple loops, post formats, and content types in a single home page template

What we have here is a Dynamic Content Gallery at the top, a YouTube video, some static content, and then two different areas for recent posts in different formats. The key here is that everything should be dynamic. We’re not looking to slap a YouTube embed in a home page template; I want to be able to use the new WordPress Post Formats to send the most recent video post to that slot whilst juggling all sorts of other dynamic content from everywhere else and — if at all possible — avoid duplicating anything. Here’s to proving it’s not impossible.

So, the first step is to take care of the DCG. This is the easy part.

12
13
14
15
16
17
	/* first, if we have dcg installed, display dcg inside it's own div */ 
if (function_exists ('dynamic_content_gallery')){ ?>
	<div id="dcg">
		<?php dynamic_content_gallery(); ?>	
	</div>
<?php } ?>

I’ve actually got featured images set up on my other pages in this theme, so if you wanted to do an else for the case where DCG didn’t exist, you could do something like this:

	/* first, if we have dcg installed, display dcg inside it's own div */ 
if (function_exists ('dynamic_content_gallery')){ ?>
	<div id="dcg">
		<?php dynamic_content_gallery(); ?>	
	</div>
<?php } else {	
// if you don't have dynamic content gallery, maybe a featured image would work?
// this is borrowing the code pretty much straight from Twentyten, so you'll need to add this to your functions.php, too
// so check with Twentyten and get that sorted first
	if ( is_singular() && current_theme_supports( 'post-thumbnails' ) &&
			has_post_thumbnail( $post->ID ) &&
			( /* $src, $width, $height */ $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'post-thumbnail' ) ) &&
			$image[1] >= HEADER_IMAGE_WIDTH ) :
		// Houston, we have a new header image!
		echo get_the_post_thumbnail( $post->ID );
	elseif ( get_header_image() ) : ?>
		<img src="<?php header_image(); ?>" width="<?php echo HEADER_IMAGE_WIDTH; ?>" height="<?php echo HEADER_IMAGE_HEIGHT; ?>" alt="" />
<?php } ?>

(Note: this part isn’t tested, per se…I’m just combining two different things I have going on in this theme. It should work, but if if borks your theme let me know, and I’ll fix my code.)

Okay, back to my code.

After DCG, I’ve got a video and static content. The static content is going to be whatever they have on their Home page. The video is the most recent video post. We’re using Post Formats so — like the featured image snippet above — you’ll need to enable that in your functions.php to get that working before you try this.

19
20
21
22
23
24
25
26
<div class="content home">
<?php /* this is the main home page stuff...there's a lot going on here 
	     first of all, we're displaying the most recent VIDEO post */ 
	query_posts( 'showposts=1' );
		if (have_posts()) : while (have_posts()) : the_post(); 
			if (has_post_format( 'video' )) { ?>	
				<div <?php post_class(); ?> id="post-<?php the_ID(); ?>"><?php the_content(); ?></div>
        <?php } endwhile; endif; rewind_posts();

So far, so good, and nothing too complex yet, right? All we’re doing here is running a loop that’s limited to 1 post, and making sure that post is a video post. Here’s where it gets fun.

27
28
29
30
31
32
33
34
35
		/* next, we're displaying the regular home page content.  That's right, you heard me, we're adding page content in between a bunch of dynamic post stuff */
		$ibm_home_page = new WP_Query('post_type=page&name=home'); 
		while ($ibm_home_page->have_posts()) : $ibm_home_page->the_post(); ?>
			<div <?php post_class('home-content'); ?>>
				<?php the_content(); ?>
			</div>
		<?php endwhile; rewind_posts(); ?>
	<div class="clear"></div>
	<hr />

I’ve completely switched over to WP_Query to be able to grab a Page with the slug ‘home’. But since I did rewind_posts, the Loop isn’t completely freaking out. Underneath this, we’ve got even more fun times.

36
37
38
39
40
41
42
43
	<?php /* down here, we're doing two more things.  First order of business is to display the next post making sure that the next post ISN'T the video post above. we're also excluding sticky posts here to get a more linear order going on. */ 
	query_posts( 'caller_get_posts=1&showposts=1' );
		if (have_posts()) : while (have_posts()) : the_post(); if (has_post_format( 'video' )) { query_posts('offset=1&caller_get_posts=1&showposts=1'); } else { ?>
			<div <?php post_class('home-excerpt'); ?> id="post-<?php the_ID(); ?>">
				<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><h2 class="the_title"><?php the_title(); ?></h2></a>
				<?php the_excerpt(); ?>
			</div>
		<?php } endwhile; endif; rewind_posts(); ?>

Woah there. It was at this point that I started running into a couple snags. First of all, I kept getting any sticky posts popping up at the top of the list, above my single post I was trying to display. This is only supposed to be a single post excerpt, so that was not going to work. Second, the next post, under my sticky post, just happened to be my video post which I created to test the video Post Format. Which is ridiculous, right? You don’t want your video and then a big empty space under your video (because I’m using the_excerpt rather than the_content) with the title of the post for…your video. And that would be bound to happen anytime you posted a video. Ninja coding skills needed to be summoned. Or, barring that, ninja Googling skills…

The first half of the query is straightforward. caller_get_posts gets the next posts in the loop sans sticky posts. Golden. And we only want one, so that part’s obvious. Next, after we do our normal loop stuff, I throw in this if (has_post_format( 'video' )) stuff that looks like it does pretty much the same thing. Well…it does. With one exception: if the next post is a video post, we’re going to offset the query by one and grab the one after that, effectively skipping your video. It’s ugly but it works, and that’s all I wanted.

This last bit is just recent updates. With all the querying and offsetting, I know we’re going to have some issues here. But I don’t care too much about this section because all I’m looking to do here is display some links from some recent posts. On another site, I might do random posts or popular posts or most commented posts here, and none of the stuff we’ve done up to now would even matter for these. Instead, what I’m doing is adding an extra offset, and if I skip a post, no big deal — chances are, that post will be featured in the DCG above, anyway.

44
45
46
47
48
49
50
51
52
53
	<div class="home-updates">
		<h2>Recent Updates</h2>
		<?php /* finally, this last section is just a recent posts area.  we care a bit less here about sticky posts or video posts, so really the only thing I'm concerned about is the offset, which i've incremented by 1 extra just in case.  this may result in some duplicates, or, alternately, some posts missing, but, again, they're just links and they're not taking up much real estate and I'm not too concerned about it */
		query_posts( 'showposts=5&offset=2' );		
			if (have_posts()) : while (have_posts()) : the_post(); ?>			
				<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><strong><?php the_title(); ?></strong></a><br />
			<?php endwhile; endif; rewind_posts(); ?>
	</div>
</div>    
<div class="clear"></div>

And there you have it. The real star of the show here is rewind_posts. If you’ve ever done multiple loops before rewind_posts came along, you’ll know that all sorts of wacky stuff can come up that throws your loop(s) off. rewind_posts allows you to use multiple loops in the same template, and then go on and do some more loops somewhere else, and nothing goes horribly awry.

Hopefully this gives someone out there some ideas of what you can do with multiple loops using query_posts. There isn’t a lot of stuff out there yet on Post Formats — particularly excluding post formats, so that was one area I sort of had to wing it. If anyone has some awesome ideas, I’d love to hear them.

(By the way, all the example text used in the mockup above comes courtesy of F*** Lorem Ipsum, which I’ve been using as an alternative to the Lorem Ipsum Generator I’ve used for years. F*** Lorem Ipsum pulls text from TV shows and commercials and is able to throw in links and line and paragraph breaks, too.)

How I fixed the “cannot redeclare _checkactive_widgets()” error in WordPress child themes

So, I had a problem.  For a while I’ve noticed a whole bunch of code being tacked on to my functions.php file.  I’ve had no idea where it came from since I certainly didn’t write it, so I generally just removed it when I saw it.  Then I noticed this weird php error when I built a child theme saying “cannot redeclare _checkactive_widgets()”.  After a few minutes, I realized that it was that same piece of code that’s been tacked onto my functions.php file, only now, since it’s a child theme with two functions.php files, it’s there twice (redeclared).  What gives?

From what I can tell, indirectly (because I’ve found zero documentation on this issue, and I’ve Googled my fingers numb trying), the _checkactive_widgets function basically looks for whatever widgets you have on your current theme and makes sure they get saved when you switch themes so you don’t have to start over.  A great idea.  But if you’re using a child theme, you get my problem.  The only thing I could think of doing is deleting that piece of code, but, from some trial and error, as far as I can tell, whenever you do just about anything in the back-end, it automagically regenerates the code.  So here’s how you fix it:

Using the “Tip for theme developers” note in the Child Themes entry in the WordPress Codex as a guide, I added this to my functions.php file:

if (!function_exists('_checkactive_widgets')) {
	// do nothing
}

This says “if the _checkactive_widgets function doesn’t exist, do nothing.” If it didn’t exist, presumably WordPress would add it in, and this prevents that. It already exists in the parent theme, and the parent’s functions.php gets run next, so this prevents overlap. This has been bugging the hell out of me for weeks, so hopefully it helps someone else.

You might also be interested in these:

  1. How to add customizable header images and customizable backgrounds to your WordPress theme
  2. Using the WordPress embed shortcode for YouTube, Vimeo, more
  3. How to upgrade your Museum Theme to the most current version after you’ve made changes to the files

How to add customizable header images and customizable backgrounds to your WordPress theme

One of the coolest new features of WordPress 3.0 is the ability to customize the site header image and background color or image. The custom header actually goes one step further and lets you set a unique header for each of your pages. This means that you can create unique headers that tie into the content of the page without complex if (is_page()) statements or hard coding them into unique page templates. The only problem is that these features need to be added into the theme for them to show up as options in your wp-admin panel and not every free (or even commercial) theme has those options set up and ready to go.

Not all themes are made for big, changeable headers, but for those that are or would adapt well, this gives users a powerful resource far beyond the custom header features that Kubrick, the previous default WordPress theme, offered with its’ ability to change the header color and gradient. Likewise, I’m tentative about giving users the ability to pick a color at random from the 16 million colors at their disposal – it’s too easy to create clashes worthy of the most gaudy GeoCities or MySpace creations. However, used with discretion and a keen eye, these features add a powerful tool to those WordPress users’ arsenal who are just itching to add a little bit of personality to their site without breaking everything.

Our newest free theme, Color Garden includes both custom headers and custom backgrounds, making it our first theme – free or otherwise – to offer both. I also played with custom headers on my recent redesign of jazzsequence.com. For the headers, it’s not the most intuitive thing to add by hand at all, and few of the resources I have found go far beyond quoting the code from TwentyTen’s functions.php file, so we wanted to give our readers just a little bit more to go on if you want to add these features to your blog theme.

Custom backgrounds are dead simple. A single line of code and you’re done:

// This theme allows users to set a custom background
add_custom_background();

Once this is included somewhere in your functions.php file, you will have a Background link under Appearance that gives you options to set a solid color for the background (by hex code or picking from a color map) or upload an file to use as a repeating background image.

Headers are a bit more complex.

To really understand how custom headers work, you need to know how post thumbnails work. Post thumbnails were added to WordPress core in 2.9 and use the built-in resizing process that happens when you upload images to create the thumbnails that will appear next to your post or post excerpt. This is presumably to replace other third-party scripts like the ubiquitous TimThumb which creates its own thumbnails and stores it in a cache folder usually located in the theme folder (although it could really be anywhere). Since WordPress 3.0, what was previously referred to as Post Thumbnail on the Add New Post page is now called Featured Image. This change is reflects the fact that the Featured Image option now controls the post thumbnail or the custom header, and the way it knows the difference is by the size of the image you are using.

Let’s take a look at how to add it to your theme and then we can revisit how to use it once it’s there. The code I will be showing comes from Color Garden although all of it has been adapted from TwentyTen (including much of the comments). Since most other posts I’ve found don’t discuss each piece of the header image function, I will go over each so you understand just what it is that you’re adding and what needs to be changed or left alone.

The first part is here:

// Your changeable header business starts here
// No CSS, just IMG call. The %s is a placeholder for the theme template directory URI.
define( 'HEADER_IMAGE', '%s/images/headers/leaves.jpg' );

The key thing to pay attention to in this snippet is the HEADER_IMAGE definition. This is the default header image. If this is left blank or set to an invalid path, no image will show up, and depending on your CSS, the layout might break. In TwentyTen this is set to %s/images/headers/path.jpg. You’ll probably want to put something here even if you plan on changing it later, and you’ll want to make sure the image actually exists where you say it exists.

The next part sets the height and width of your header image:

// The height and width of your custom header. You can hook into the theme's own filters to change these values.
// Add a filter to twentyten_header_image_width and twentyten_header_image_height to change these values.
define( 'HEADER_IMAGE_WIDTH', apply_filters( 'cg_header_image_width', 1000 ) );
define( 'HEADER_IMAGE_HEIGHT', apply_filters( 'cg_header_image_height', 343 ) );
 
// We'll be using post thumbnails for custom header images on posts and pages.
// We want them to be 1000 pixels wide by 343 pixels tall.
// Larger images will be auto-cropped to fit, smaller ones will be ignored. See header.php.
set_post_thumbnail_size( HEADER_IMAGE_WIDTH, HEADER_IMAGE_HEIGHT, true );

Notice that we’re using set_post_thumbnail_size with the header image’s dimensions. This is because the custom header function uses the existing post thumbnails function from 2.9 and builds onto it. As the comments indicate, images that are equal to or larger than the height and width definitions will be resized to fit and set as the header image when you add it to your post or page. Anything smaller will be ignored and set as the post thumbnail (if post thumbnails are enabled).

The last part of the custom header function is this:

// Don't support text inside the header image.
define( 'HEADER_TEXTCOLOR', '' );
define( 'NO_HEADER_TEXT', true );
// ... and thus ends the changeable header business.

The NO_HEADER_TEXT and HEADER_TEXTCOLOR add the ability to change the color of the text that appears in the header. The alternative (pulled from the WordPress Codex) would be to use:

define('HEADER_TEXTCOLOR', 'ffffff');

and omitting the NO_HEADER_TEXT line.

Now this part is done, you’ve enabled custom headers and defined a default. But what if you want to have multiple defaults like TwentyTen? In that case, we go back to TwentyTen’s functions and keep digging:

// Default custom headers packaged with the theme. %s is a placeholder for the theme template directory URI.
register_default_headers( array(
 
'leaves' =&gt; array(
'url' =&gt; '%s/images/headers/leaves.jpg',
'thumbnail_url' =&gt; '%s/images/headers/leaves-thumbnail.jpg',
/* translators: header image description */
'description' =&gt; __( 'Leaves', 'cg' )
),
 
'sunset' =&gt; array(
'url' =&gt; '%s/images/headers/sunset.jpg',
'thumbnail_url' =&gt; '%s/images/headers/sunset-thumbnail.jpg',
/* translators: header image description */
'description' =&gt; __( 'Sunset', 'cg' )
),
 
'beach' =&gt; array(
'url' =&gt; '%s/images/headers/beach.jpg',
'thumbnail_url' =&gt; '%s/images/headers/beach-thumbnail.jpg',
/* translators: header image description */
'description' =&gt; __( 'Beach', 'cg' )
),
 
'blueberries' =&gt; array(
'url' =&gt; '%s/images/headers/blueberries.jpg',
'thumbnail_url' =&gt; '%s/images/headers/blueberries-thumbnail.jpg',
/* translators: header image description */
'description' =&gt; __( 'Blueberries', 'cg' )
)
) );

Again, we’re looking at the code from Color Garden but it’s adapted from TwentyTen’s functions.php. Each item in the array above defines one of the default header image options. Color Garden has four default headers to choose from to go with the four color schemes built into the theme. All we’re really doing here is adding the path to the image, the path to the thumbnail of the image that appears on the Headers page in the WordPress backend, and the description which – as far as I have been able to tell – really only affects the alt text of the image in the backend.

All said, what you should be looking at in your functions.php file when you’re done is this (if you’re including multiple default header images):

// Your changeable header business starts here
// No CSS, just IMG call. The %s is a placeholder for the theme template directory URI.
define( 'HEADER_IMAGE', '%s/images/headers/leaves.jpg' );
 
// The height and width of your custom header. You can hook into the theme's own filters to change these values.
// Add a filter to twentyten_header_image_width and twentyten_header_image_height to change these values.
define( 'HEADER_IMAGE_WIDTH', apply_filters( 'cg_header_image_width', 1000 ) );
define( 'HEADER_IMAGE_HEIGHT', apply_filters( 'cg_header_image_height', 343 ) );
 
// We'll be using post thumbnails for custom header images on posts and pages.
// We want them to be 1000 pixels wide by 343 pixels tall.
// Larger images will be auto-cropped to fit, smaller ones will be ignored. See header.php.
set_post_thumbnail_size( HEADER_IMAGE_WIDTH, HEADER_IMAGE_HEIGHT, true );
 
// Don't support text inside the header image.
define( 'HEADER_TEXTCOLOR', '' );
define( 'NO_HEADER_TEXT', true );
 
// ... and thus ends the changeable header business.
 
// Default custom headers packaged with the theme. %s is a placeholder for the theme template directory URI.
register_default_headers( array(
 
'leaves' =&gt; array(
'url' =&gt; '%s/images/headers/leaves.jpg',
'thumbnail_url' =&gt; '%s/images/headers/leaves-thumbnail.jpg',
/* translators: header image description */
'description' =&gt; __( 'Leaves', 'cg' )
),
 
'sunset' =&gt; array(
'url' =&gt; '%s/images/headers/sunset.jpg',
'thumbnail_url' =&gt; '%s/images/headers/sunset-thumbnail.jpg',
/* translators: header image description */
'description' =&gt; __( 'Sunset', 'cg' )
),
 
'beach' =&gt; array(
'url' =&gt; '%s/images/headers/beach.jpg',
'thumbnail_url' =&gt; '%s/images/headers/beach-thumbnail.jpg',
/* translators: header image description */
'description' =&gt; __( 'Beach', 'cg' )
),
 
'blueberries' =&gt; array(
'url' =&gt; '%s/images/headers/blueberries.jpg',
'thumbnail_url' =&gt; '%s/images/headers/blueberries-thumbnail.jpg',
/* translators: header image description */
'description' =&gt; __( 'Blueberries', 'cg' )
)
) );

What I haven’t said yet is that in every instance that cg appears in the code, this specifically references Color Garden. In TwentyTen it’s twentyten. You can put whatever you want here so long as it remains internally consistent.

After you’ve got your functions.php set up, you still need to add in some code in your header.php to actually display the custom header image. What we have in Color Garden is taken almost verbatim out of TwentyTen.

	  <?php
          // Check if this is a post or page, if it has a thumbnail, and if it's a big one
          if ( is_singular() &&
                  has_post_thumbnail( $post->ID ) &&
                  ( /* $src, $width, $height */ $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'post-thumbnail' ) ) &&
                  $image[1] >= HEADER_IMAGE_WIDTH ) :
              // Houston, we have a new header image!
              echo get_the_post_thumbnail( $post->ID, 'post-thumbnail' );
          else : ?>
              <img src="<?php header_image(); ?>" width="<?php echo HEADER_IMAGE_WIDTH; ?>" height="<?php echo HEADER_IMAGE_HEIGHT; ?>" alt="" class="masthead" />
          <?php endif; ?>

This is where the theme asks “what is the size of the featured image?” and, based on the size, determines whether it is a header image or a post thumbnail.

Now, obviously there needs to be some CSS styling involved and you may or may not want your header image to be 1000 pixels wide by 343 high like ours is in Color Garden. We added a “masthead” class to the image so we could isolate styles to our header image. But, if you’ve made it this far, you’ve got everything you need to tweak the code to suit your theme. The custom headers function is exciting because it doesn’t need to be limited to just header images. You can use it wherever you might want a customizable image in your theme, and there’s more than a few creative uses I can think of beyond headers for something like that.

You might also be interested in these:

  1. How I fixed the “cannot redeclare _checkactive_widgets()” error in WordPress child themes
  2. How to upgrade your Museum Theme to the most current version after you’ve made changes to the files
  3. 12 Free WordPress Themes I Like (and you should, too)

add social links to your site

class=”aligncenter” i spent this morning building and adding some social linking to our site.  with all the digging and twittering and facebooking going on, if you have content worth sharing and you aren’t providing ways for people to share it, it’s fairly likely that people won’t.  now, i have digg, facebook, and delicious bookmarklets in my google chrome bookmark bar, but i realize that i’m a geek and probably most people don’t do this.  and anyway, it’s always nicer when those things are built directly into the page.

so i thought that i would share with you how to add social linking to your website or blog.  please note that some of the code here will be wordpress-specific — which is great for wordpress users, but won’t be so helpful for those of you who don’t use wordpress.  i will point out the areas where the code is wordpress only — there are plenty of resources out there for alternatives for your platform of choice.

the icons

first thing’s first — let’s get some icons.  obviously the ones we are using have been customized.  i actually sort of cheated a bit and modified the grunged-up icons i used for the social sidebar i have on jazzsequence.com, because i thought the style would fit.  and also, i’m doing the same thing over there, so i figured i’d just use the same icons to make my life a bit easier.  so you can’t use mine, but there’s some really nice stuff out there — i used a pack i found on iconspedia, but there’s always some good stuff on smashing magaine among other sources.  do some creative googling and you can find some awesome packs with the sites you want to share.

the template files

next, is tweaking the template files.  if you’ve never even looked at your theme’s php files, this can be daunting at first.  and if you don’t have at least some brief experience in html, this may not be for you (but it might, you never know until you give it a try and break something horribly! keep backups of everything!).  in that case, i’d recommend the sociable plugin, which actually allows you to take the icons you just downloaded and put them somewhere on your server and then just enter the path to the folder that you uploaded them to.  you get less customizability in how and where your social linking bookmarks go on the page, but you make up for that in choice and convenience (there’s something like 99 different sharing methods to choose from that sociable offers).

if you’re still with me, decide what pages you want your links to show up on.  for the arcane palette site, i chose to just put them on the single post page, but you can put them on all your pages, blog, and single posts, as well as any custom templates you may be using.  there are two ways of editing the code.  in either case, it’s best to save a backup copy of all the files you’re going to be changing in case something breaks or you want to put it back.  the first method is to do it directly from the wordpress backend.  this is a little bit more sketchy for newbies just because you are making changes live on the site.  however, if you saved a copy of the file before making any changes to it, then you should be fine.

so to get to the internal text editor, (assuming you have wordpress 2.7 or higher) you go to Appearance and then Editor (for older versions it’s in Design and then Editor, or possibly Theme Editor — it’s been a while since I’ve dug around in the older back end).  on the right side, you will see a long list of files.  these are all the various page templates on your site.  the ones you want to concern yourself with are index.php (Main Index Template), page.php (Page Template), and single.php (Single Post).  if you’re using a Revolution/StudioPress theme, or one that is built similar, you may have a home.php which is your Home Page Template.

some of this, if you aren’t familiar with how your theme is structured, is going to be a bit of trial and error, but pretty much I look for one of two things in the template: either the Edit This Post link (which will look something like this:

<?php edit_post_link('Edit this entry.', '<p>', '</p>'); ?>

or the metatag portion of the post, generally classed as postmeta or something similar, which would be something like this:

<p>
<small><?php the_category(', ') ?> | <?php the_tags() ?></small>
</p>

you may also see something like this if your theme is either the default (kubrick) theme, or based somewhat on it:

This entry was posted
<?php /* This is commented, because it requires a little adjusting sometimes.
You’ll need to download this plugin, and follow the instructions:
http://binarybonsai.com/archives/2004/08/17/time-since-plugin/ */
/* $entry_datetime = abs(strtotime($post->post_date) – (60*120)); echo time_since($entry_datetime); echo ‘ ago’; */ ?>
on <?php the_time(‘l, F jS, Y’) ?> at <?php the_time() ?>
and is filed under <?php the_category(‘, ‘) ?>.
You can follow any responses to this entry through the <?php post_comments_feed_link(‘RSS 2.0’); ?> feed.
This entry was posted
<?php /* This is commented, because it requires a little adjusting sometimes.
You'll need to download this plugin, and follow the instructions:
http://binarybonsai.com/archives/2004/08/17/time-since-plugin/ */
/* $entry_datetime = abs(strtotime($post->post_date) - (60*120)); echo time_since($entry_datetime);
echo ' ago'; */ ?>
on <?php the_time('l, F jS, Y') ?> at <?php the_time() ?>
and is filed under <?php the_category(', ') ?>.
You can follow any responses to this entry through the <?php post_comments_feed_link('RSS 2.0'); ?>
feed.

for our site, i put it under the post meta (categories/tags) but above the related posts.  interesting side note: if you’re using this method of displaying related posts without a plugin, i was having issues with the tweet this link posting the url of the last related post in the tweet, rather than the post you are looking at if you put this sharing block underneath the related posts.  seemed to be a bug with the related posts not closing off, but i’m not a programmer, i’m just a hacker, so i just threw this block above those links and solved the problem.

the code

here’s the block of code i used:

<span class="linktous">
<a href="javascript:var notes='';if(window.getSelection)notes=window.getSelection();else
if(document.getSelection)notes=document.getSelection();else if(document.selection)notes=
document.selection.createRange().text;if(notes.length>350)notes=notes.substring(0,349);
location.href='http://digg.com/submit?phase=3&url='+encodeURIComponent(location.href)+
'&title='+encodeURIComponent(document.title)+'&bodytext='+encodeURIComponent(notes)"
target="_blank"><img src="<?php bloginfo('template_url'); ?>/images/digg.png" alt="Digg
This" />&nbsp;Digg This Post</a>&nbsp;|&nbsp;<a href="javascript:(function(){location.
href='http://delicious.com/save?url='+encodeURIComponent(window.location.href)+'&title=
'+encodeURIComponent(document.title)+'&v=5&jump=yes'})()" target="_blank"><img src="<?php
bloginfo('template_url'); ?>/images/delicious.png" alt="Save to del.icio.us" />&nbsp;Save
to del.icio.us</a>&nbsp;|&nbsp;<a href="javascript:var d=document,f='http://www.facebook.
com/share',l=d.location,e=encodeURIComponent,p='.php?src=bm&v=4&i=1239647138&u='+e(l.href)+
'&t='+e(d.title);1;try{if (!/^(.*.)?facebook.[^.]*$/.test(l.host))throw(0);
share_internal_bookmarklet(p)}catch(z) {a=function() {if (!window.open(f+'r'+p,'sharer',
'toolbar=0,status=0,resizable=1,width=626,height=436'))l.href=f+p};if (/Firefox/.test
(navigator.userAgent))setTimeout(a,0);else{a()}}void(0)" target="_blank"><img src="<?php
bloginfo('template_url'); ?>/images/facebook.png" alt="Share on Facebook" />&nbsp;Share
on Facebook</a>&nbsp;|&nbsp;<a href="http://twitter.com/home?status=Check this out: <?php
the_title(); ?> <?php bloginfo('url'); ?>/?p=<?php the_ID(); ?>" target="_blank"><img
src="<?php bloginfo('template_url'); ?>/images/twitter.png" alt="Send this page to Twitter"
/>&nbsp;Tweet This</a>&nbsp;|&nbsp;<a href="<?php bloginfo('rss_url'); ?>" target="_blank">
<img src="<?php bloginfo('template_url'); ?>/images/rss.png" alt="Subscribe by RSS" />&nbsp;
Subscribe by RSS</a>
</span>

that’s a big mess of code in several different languages, so i’ll break it down so you can see what each thing is doing.  also, this assumes that you’ve uploaded your images to the /images folder in your theme and that you are using the same links i am, namely: digg, delicious, facebook, twitter, and for kicks, rss.  i’ll post the code for stumbleupon as well at the end.

span

<span class="linktous">

first, i put everything in a span which i named “linktous”.  this is to make it identifiable later, but also because i add a few css tweaks later, which i’ll get to.  the span isn’t absolutely important, but you’ll find you need it (or something similar) if you want to move stuff around at all.

digg

<a href="javascript:var notes='';if(window.getSelection)notes=window.getSelection();else
if(document.getSelection)notes=document.getSelection();else if(document.selection)notes=
document.selection.createRange().text;if(notes.length>350)notes=notes.substring(0,349);
location.href='http://digg.com/submit?phase=3&url='+encodeURIComponent(location.href)+
'&title='+encodeURIComponent(document.title)+'&bodytext='+encodeURIComponent(notes)"
target="_blank"><img src="<?php bloginfo('template_url'); ?>/images/digg.png" alt="Digg
This" />&nbsp;Digg This Post</a>&nbsp;

here’s the digg code.  this particular javascript link allows you to select a portion of the text which will be auto-filled in your digg submission when it sends you there.  not that you need to tell your users that or anything, but you can if you want and it’s pretty neat.  otherwise you can find another digg link that doesn’t do that if you really want, but if nothing is selected, then obviously nothing will be copied, and i’m willing to be that most people will have already selected text anyway because they will be copying and pasting text from the page into digg.  when they get there, they’ll get a little happy surprise.

there isn’t anything major to this link, since the javascript code inside the href does all the heavy lifting.  if you take a look at the end in the img tag, you’ll see that rather than typing in a long path to the image, i used wordpress shortcode.  there’s lots of stuff you can do with <?php bloginfo() ?> which you can read about in the wordpress codex.  a lot of themes will use bloginfo(‘url’) for everything, but that just gives you the main url to the site.  bloginfo(‘template_url’) or bloginfo(‘stylesheet_directory’) send you to the folder of the theme you’re using.  i uploaded all my icons to my theme’s /images folder, so this makes it easy for me, but if you made a folder called “images” just in the root directory, you could do <?php bloginfo(‘url’); ?>/images/youricon.png and be able to easily use the same code if you changed themes.  also, if you haven’t seen or used it before, &nbsp; is the ascii code for a space.  since the code is a big messy beast, i want to make sure there’s the right spacing between my images and the link text.  i could do this with css, but i wanted to keep the css to a minimum so i could easily reuse the code.

del.icio.us and facebook

|&nbsp;<a href="javascript:(function(){location.
href='http://delicious.com/save?url='+encodeURIComponent(window.location.href)+'&title=
'+encodeURIComponent(document.title)+'&v=5&jump=yes'})()" target="_blank"><img src="<?php
bloginfo('template_url'); ?>/images/delicious.png" alt="Save to del.icio.us" />&nbsp;Save
to del.icio.us</a>&nbsp;

another javascript link that sends you to a delicious submit page.  the links, you’ll notice, are separated by a pipe or |.  it’s a key on your keyboard that you probably don’t even know is there if you’re not a programmer or a hacker.  other than that, and the stuff from above which i’m continuing to use, there’s nothing to see here, or here, when we get to facebook:

|&nbsp;<a href="javascript:var d=document,f='http://www.facebook.
com/share',l=d.location,e=encodeURIComponent,p='.php?src=bm&v=4&i=1239647138&u='+e(l.href)+
'&t='+e(d.title);1;try{if (!/^(.*.)?facebook.[^.]*$/.test(l.host))throw(0);
share_internal_bookmarklet(p)}catch(z) {a=function() {if (!window.open(f+'r'+p,'sharer',
'toolbar=0,status=0,resizable=1,width=626,height=436'))l.href=f+p};if (/Firefox/.test
(navigator.userAgent))setTimeout(a,0);else{a()}}void(0)" target="_blank"><img src="<?php
bloginfo('template_url'); ?>/images/facebook.png" alt="Share on Facebook" />&nbsp;Share
on Facebook</a>&nbsp;

the facebook share opens a new window, so the javascript link is a bit bigger, but otherwise it’s the same stuff we’ve been doing above.

twitter

|&nbsp;<a href="http://twitter.com/home?status=Check this out: <?php
the_title(); ?> <?php bloginfo('url'); ?>/?p=<?php the_ID(); ?>" target="_blank"><img
src="<?php bloginfo('template_url'); ?>/images/twitter.png" alt="Send this page to Twitter"
/>&nbsp;Tweet This</a>&nbsp;

twitter was a bit trickier because of the character limit.  if you’re using pretty permalinks, and you have a url that’s something like http://mydomain.com/wordpress-tricks/how-to-add-an-awesome-social-link-block-to-your-blog/, that’s going to take up most of your character limit with the url alone.  so i started looking for url shortening in a tweet this type code and, while i didn’t find it, this guy had an idea that reminded me that wordpress has a form of url shortening built in.  sort of.  as he explains in his method of creating a tweet this link from your wordpress blog with shortened urls, when you first setup wordpress, all your blog post urls look like this:


http://yourblog.com/?p=123


the part after the ?p= is the ID number of the blog post.  his method describes how to add a url rewriting rule to your .htaccess file so you could do really short urls like this:

http://iboughtamac.com/s/1352

i didn’t want to bother with editing the .htaccess file, especially since the original url is both still entirely functional even with pretty permalinks turned on, and just as short, really.  so here’s the link that i am sending to twitter:

<?php bloginfo('url'); ?>/?p=<?php the_ID(); ?>

first, i get the base url of the site.  it helps (for shortening purposes) if you’ve set the url of your blog in the general settings in your wordpress admin to be http://yourdomain.com rather than http://www.yourdomain.com, but it’s no big — it’s just 3 characters.  so then i added the /?p= to make the url mimic the old-style, ugly permalink.  i follow this by adding the wordpress shortcode to get the ID of the post.  so the url of this post would be:

http://arcanepalette.com/?p=455

not too shabby, eh?  it’s got nothing on http://is.gd/14wmq in terms of brevity, but it’s still pretty good.  twitter is pretty easy because you can send posts to twitter via just about anything.  you can type out your post in your address bar if you were really so inclined.

finishing touches

|&nbsp;<a href="<?php bloginfo('rss_url'); ?>" target="_blank">
<img src="<?php bloginfo('template_url'); ?>/images/rss.png" alt="Subscribe by RSS" />&nbsp;
Subscribe by RSS</a>
</span>

i chose to add an rss subscription link to each single post as well, as a way to remind people that they can always subscribe by rss.  getting rss subscribers is a good thing because it brings your site’s visitors back, even if they aren’t actually hitting the site.  once again, i’m using wordpress shortcode to handle the rss url (bloginfo(‘rss_url’)).  if you’re using feedburner and have the feedsmith plugin installed, this will work for you, however, if you don’t have the feedsmith plugin, substitute the <?php bloginfo(‘rss_url’); ?> with your feedburner url.  also, i closed off the span i started at the beginning.

i mentioned earlier that i added some css tweaking.  i wanted my icons to be a bit bigger to make them more visible.  usually when you see buttons like this, they are the standard favicon size of 16×16, but that’s really small.  i made mine 20×20 which isn’t that much bigger but it does make it a bit easier to see what they are and notice that there’s some texture to them.  because of this, i needed to add some css to make the icons vertically centered with the text.  so i added this to my style.css:

.linktous img{margin-bottom: -3px;}

this pulls the icons a few pixels down and levels it out a bit.  i also added a .linktous {text-transform: lowercase;} to make all the text, well, lowercase.  this is purely for aesthetic reasons.

stumbleupon

if you wanted to include a stumbleupon button as well, here’s the url, pulled directly from their button generator thingie:

http://www.stumbleupon.com/submit?url=<?php the_permalink(); ?>&title=<?php the_title(); ?>

so to put it in the same style as everything else, you’d do something like this

|&nbsp;<a href="http://www.stumbleupon.com/submit?url=<?php the_permalink(); ?>&title=<?php the_title(); ?>"
target="_blank"><img src="<?php bloginfo('template_url'); ?>/images/stumbleupon.png" alt="Stumble This" />
&nbsp;Stumble This</a>

conclusion

why go through all the effort if, as previously mentioned, sociable does something really similar?

one reason is aesthetics and control.  this way i can style the links the way i want and put them where i want and not have resign myself to doing it however the plugin-du-jour happens to do things.

another reason is experience and because i like to get my hands dirty.  if you’ve gotten this far, i imagine you like to get your hands dirty as well, or at least are interested in learning more about how to build and/or customize wordpress themes.

the last reason is stability.  i learned (the hard way!) from using tons of firefox extensions that doing so doesn’t exactly result in the most stable (or fast) environment.  taking care of the code myself and embedding it into the theme rather than tacking on yet another plugin is one less complication, one less thing to upgrade, and one less thing that can break.

so that about wraps up this lesson.  i hope you found this useful and feel free to use the fabulous links below to share this post if you did!