Add DZone widget to selected posts only in WordPress
by Stii
DZone is a great resource for developers. Lots and lots of valuable articles. Thing is, on my blog, not all posts are technical of nature, thus I don’t want the DZone widget to display on all of them. I want the widget to only display on posts that may be worthy and that are of a technical nature. Here is how I’ve done it with WordPress using custom fields.
WordPress allows you to add custom fields to your posts. This is potentially very handy, but not always widely used or implemented. I created a custom field called dzone and set it’s value to yes.


I then edited my WordPress theme to check whether the custom field is selected on a post:
<?php $show_dzone = get_post_meta($post->ID, "dzone", true);
The get_post_meta() function allows me to get all custom fields of a post. In this instance I passed 3 parameters to it. The post ID, the key or name of the custom field and set the third to true so that it returns the value of the key as a string. If that is not set or set as false, it would return an array. (Keep that in mind)
All you need to do next is to test whether $show_dzone is set. If it is not set, it won’t display anything. If it is set, it would assign the necessary values, like the url and title, to the DZone javascript and display it with your post.
if (!empty($show_dzone)): ?>
<script type="text/javascript">
var dzone_url = '<?php the_permalink() ?>';
var dzone_title = '<?php the_title() ?>';
var dzone_style = '2';
</script>
<script language="javascript" \
src="http://widgets.dzone.com/widgets/zoneit.js">
</script>
<?php endif; ?>
This is by no means an ideal solution and a plugin would be more useful, I’ll admit that. Should you want to do this however, here is a text file with the snippet of code you can simply copy and paste into your template files. Note that if you do it this way, you’ll have to insert the code on all template files that display a post like the index.php, search.php and single.php.