How to Add a Digg Button to a WordPress Post

See the Digg button? {[ 1.diggthis() ]} is the enzyme I wrote for displaying it. I think it’s useful to have a means for adding a Digg button to a post only when and where you need it.

Of course you can put the same enzyme in a template (using the metabolize function), and you’ll see a Digg button into each and every post, but I prefer the on-demand way.

Now I’ll show you my setup.

1. Add a ‘diggthis-code’ custom field

As usual, I add the enzymes I’m going to use over and over, into the post number 1, the one that WordPress gives you by default.

This custom field is for the code that Digg tells you to use. I prefer to isolate external codes into their own custom fields, so this one is just for that:

<script type="text/javascript">
digg_url = 'WEBSITE_URL';
digg_title = 'TITLE';
</script>
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script>

2. Add a ‘diggthis’ custom field

This custom field is for the enzyme:

$post = $this->post;
$url = post_permalink( $post->ID );
if( false !== strpos( $url, '://localhost/' ) ) {
  return '[no digg for localhost]';
}
$title = $post->post_title;
$code = $this->elaborate( "1.diggthis-code" );
$code = $code[0];
$code = str_replace( 'WEBSITE_URL', $url, $code );
$code = str_replace( 'TITLE', $title, $code );
$style = $this->substrate;
if( '' != $style ) {
  $style = ' style="' . $style . '"';
}
$code = '</p><div class="diggthis"' . $style . '>' . $code . '</div><p>';
//return htmlspecialchars( $code );
return $code;

  • Line 1: get the current post object
  • Lines 2-6: get values for the variables of the widget
    the localhost shortcircuit is a Digg requirement; if you don’t return, you’ll see an error
  • Lines 7-10: get the widget and set its variables
  • Lines 11-14: get custom style from the enzyme’s substrate, if any
  • Line 15: decorate the widget
    reverse P-wrap is needed because WordPress automatically applies a P-wrap and a DIV into a P is not allowed
  • Line 16: useful for debugging
  • Line 17: return the widget

3. Use it

That’s it. For displaying a new Digg button now, right here

I wrote {[ 1.diggthis( =float: right; margin-left: 1em;= ) ]}. This time I overwrite the CSS for the class diggthis that I put into my theme:

.diggthis {
	float: left;
	margin-right: 1em;
}

Prior art

Leave a Reply

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