Skip to content

Instantly share code, notes, and snippets.

@soska
Created December 11, 2009 07:17
Show Gist options
  • Save soska/254047 to your computer and use it in GitHub Desktop.
Save soska/254047 to your computer and use it in GitHub Desktop.
Simple Wordpress plugin that link hashtags in posts to wp-tags
<?php
/*
Plugin Name: WpHashTags
Plugin URI: http://duperrific.com/
Description: Links twitter-style #hashtags into wordpress tags. Does not check if the tag exists tho.
Author: Armando Sosa
Version: 0.1
Author URI: http://armandososa.com/
*/
class WpHashTags{
var $stripHashes = false;
function hashIt($content, $stripHashes = null){
if ($stripHashes) {
$this->stripHashes = $stripHashes;
}
// I use the ampersand to catch entities and later discard them
// if somebody knows a more efficient way to do it in code, please tell me
$pattern = "/(&?#[^\s|^,]+(\s[^\#|^\s]+#)?)/";
$content = preg_replace_callback($pattern,array(&$this,'replaceCallback'),$content);
return $content;
}
function replaceCallback($matches){
$match = $matches[0];
// just in case we matched an html entity, we discard it.
if (strpos($match,'&') === 0) {
return $match;
}
$tag = str_replace('#','',$match);
if ($this->stripHashes) {
$match = $tag;
}
$tag = strtolower(str_replace(' ','-',$tag));
$hashtag = $match;
$link = $this->getLink($tag);
return "<a href='$link'>$hashtag</a>";
}
function getLink( $tag ) {
global $wp_rewrite;
$taglink = $wp_rewrite->get_tag_permastruct();
if ( empty( $taglink ) ) {
$file = get_option( 'home' ) . '/';
$taglink = $file . '?tag=' . $tag;
} else {
$taglink = str_replace( '%tag%', $tag, $taglink );
$taglink = get_option( 'home' ) . user_trailingslashit( $taglink, 'category' );
}
return $taglink;
}
}
function wp_hash_tags($content){
$o = new WpHashTags;
return $o->hashIt($content);
}
add_action('the_content','wp_hash_tags');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment