Tag: plugin

How to write a WordPress plugin to notify your customers via Twitter.

WordPress has a page on “Writing a Plugin” that you can refer to for all the gory details; this post is a quick demonstration of how you too can notify people of updates to your Blog via Twitter.

Add your handlers:


Add some check boxes to the “Write Post” interface:

function notify_customers_checkbox()
<fieldset id="notify_customers" class="dbx-box">
<h3 class="dbx-handle">Notify Customers:</h3>
<div class="dbx-content">
<input type="checkbox" name="send_to_twitter" id="send_to_twitter" checked="checked" /> twitter
<input type="checkbox" name="send_to_list" id="send_to_list" checked="checked" /> email
<input type="checkbox" name="send_to_nntp" id="send_to_nntp" checked="checked" /> nntp

Check the status of those check boxes:

function notify_customers($post_id)
if ( isset ( $_POST['send_to_twitter'] ) )
{ send_to_twitter($post_id); }

if (isset ( $_POST['send_to_list'] ) )
{ send_to_list($post_id); }

if (isset ( $_POST['send_to_nntp'] ) )
{ send_to_nntp($post_id); }

Write a method to take your post, clean it up a bit and send it off to Twitter:

function send_to_twitter($post_id)
$twitter_user = 'sonicnet_status';
$twitter_pass = '';

$post_url     = get_permalink($post_id);
$post_title    = stripslashes($_POST['post_title']);
$post_title    = html_entity_decode($post_title);
$post_content    = stripslashes($_POST['post_content']);
$post_content    = strip_tags($post_content);
$post_content    = html_entity_decode($post_content);

$twitter_message = "$post_title: $post_content";

// We only care about published posts.
// If it's an old post being updated prepend "Update" to the post.

if ( $_POST['prev_status'] == 'draft' ) //new post.
if($_POST['publish'] == 'Publish')
$xrl = file_get_contents("http://metamark.net/api/rest/simple?long_url=$post_url");

$twitter_message = substr($twitter_message , 0 , 117);
$twitter_message = "$twitter_message... $xrl";
$twitter_message = urlencode($twitter_message);

$url = 'http://twitter.com/statuses/update.xml';
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, "$url");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$twitter_message");
curl_setopt($curl_handle, CURLOPT_USERPWD, "$twitter_user:$twitter_pass");
$buffer = curl_exec($curl_handle);

And there you have it; you’ve just told all your Twitter followers about your latest Blog post.

You’ll note we do some other cool stuff to keep our customers in the loop; like send them E-Mail and post to Usenet, but that’s another Blog post.