February 5, 2010

Safe mailto links in Wordpress using CodeIgniter

Recently I did a half-way makeover of my site/blog that included removing the contact page that only one, count them, one person ever used. Now granted it was a guy from Microsoft I had recently met and contacted me about a job opportunity, I never the less decided to get rid of the whole contact page thing and simply put an email link in my about page.  Wanting to obfuscate it from evil email harvesters, Wordpress by default doesn’t offer a easy way of doing this within a post.  That’s where the Wordpress shortcode API and CodeIgniter come in.

Wordpress has a cool feature that allows you to create shortcodes to put in your posts like [bartag foo="foo-value"] and then process it using a PHP function.   Go to the codex page and check it out, it’s pretty straight forward.  Next go grab you a copy of CodeIgniter, crack it open and go to system/helpers/url_helper.php.  Snatch the safe_mailto() function and paste it in your code.  I put mine in the functions page in the theme for quickness but you can put it in a plug in if your up for all that.  Now underneath the CI function ,  write you a function that takes the attributes and content from the shortcode and then call the safe_mailto() function.  You should end up with something like below. That’s it! Now you can have protected and obfuscated email links in your posts!

//The CodeIgniter function
if ( ! function_exists('safe_mailto'))
{
	function safe_mailto($email, $title = '', $attributes = '')
	{
		// The actual function. You get the drift...
	}
}

// The function to process the shortcode
function maillink_func($atts, $content = null) {
	extract(shortcode_atts(array(
		'email' => get_bloginfo ( 'admin_email' ),
                'title' => null,
                'class' => null,
                'id'    => null,
                'style' => null
                //add more attributes if you want them, but add below too!
	), $atts));

        return safe_mailto($email, $content, array(
                'class' => $class,
                'id' => $id,
                'style' => $style
            ));
}

//Register the shortcode with Wordpress
add_shortcode('maillink', 'maillink_func');

// Usage
// [maillink email="someone@somewhere.com"]
// [maillink email="someone@somewhere.com" class="link"]Email Me![/maillink]