My First WordPress Plugin
I've been meaning to do this for a while, I'm writing a plugin for wordpress to automatically capitalize the right letter in the words I'm generally lazy about typing. Things like I, I'm, I've and the like[1].
Took me a little while but I did finally find some documentation on all the different hooks wordpress has for filters. I found one in particular that does what I want called content_save_pre which applies a particular filter to the content of a post any time I save or edit it. So for things like drafts and actual posting and updating posts it would fire the function I registered as a filter.
The first problem I ran into is that for some strange reason it didn't seem to want to replace contractions with the single quote character. I later found out that when displaying the single-quote it converts it to the html entity ’ which shows up as an apostrophe. So I tried working around that but that dIdn't seem to work either. Eventually I just setup a small test post and modified the function to email me the plain-text contents of the post that the filter would receIve, I noticed that it escaped single quotes probably through the use of the php function mysql_escape_string[2]. So anything with an single-quote would show up with a backslash just before the single-quote. This of course broke the regular expression I was using and I couldn't seem to figure out how to get it to check for that character so I gave up and just used the negated word-character class \W.
Anyway after fiddling around with it a little more and adding a few new cases to the regex I arrived at this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php /* Plugin Name: Lazy Errors Plugin URI: http://www.bemasher.net/ Description: Replaces errors from lazy typing, things like: I, I'd, I've, I'm will be replaced with proper case. Version: 0.02 Author: BeMasher Author URI: http://www.bemasher.net/ */ function lazy_errors($content) { return preg_replace("/I(?(?=\W')(\W')(ve|m|d|)|(\b))/", "I$1$2$3", $content); } add_filter("content_save_pre", "lazy_errors"); ?> |
The regular expression reads like so: If there's an I followed by any non-word character and a single-quote then make sure it's got a proper contraction following the single-quote. Else make sure there's a space, period, comma, colon or semI-colon following the I. Then replace with capitalized I and the matching group from the conditional.
I should probably work out some code to make it ignore sections of text I don't want it to filter. A prime example of this would be in the comments of the plugin and especially in any code as code examples copied from my site would then be broken if the regex I wrote matched anything in the code.
- Notice they look normal to you because I've gotten my script working. [↩]
- http://www.php.net/manual/en/function.mysql-escape-string.php [↩]
