Don’t Break The Code

Last Saturday at WordCamp Philly, I ran a session on “Building a Plugin in One Night”. Together, with about 50+ attendees, we brainstormed ideas for a new WordPress plugin that I could code that night.

The brainstorming went great, coming up with some good ideas… like plugins to:

  • Help first responders after a disaster (Big Idea!)
  • Add VIM (a Linux editor) shortcut commands to the Visual Editor
  • Disable the Visual Editor on a per-post basis (The Winner)
  • Allow users to create pages from the front end
  • Add easy donations
  • Log into WordPress via Google+ (Brian did it!)
  • Add syntax highlighting to the Visual Editor (Chris did it!)

The concept that the audience voted for me to work on was a way to disable the Visual Editor tab on a per-post basis. The motivation for this is the fact that the autoformatting of the Visual tab will sometimes break a complicated (or not so complicated) HTML structure ruining your code. Folks wanted a way to say, “Hey, WordPress, back off on this page/post.”

And someone (you introduced yourself to me later, but I forget your name) came up with a kick ass name: Don’t Break the Code. It explains the purpose and also harkens back to my days at Haverford College, which has a strong social/academic honor code.

I had hoped for something a little more mainstream. Only a developer or power user will really appreciate a plugin to disable the Visual tab, but that’s okay. The effort would be appreciated.

Turns out there are already a few plugins that either disable the Visual tab or remove other filters to keep WordPress from breaking code. The started trickling in after the presentation wrapped:

… and probably a few more. So we weren’t blazing new ground.

Still, some good ideas came up during the session that could improve the experience of using a plugin like this. Like:

  • Put the checkbox to disable the editor in the screen options area so it doesn’t clutter up the editor
  • Only allow admins to disable the editor. Other roles will see what the admin chose.
  • Allow admins to add a note RE why the Visual Editor is disable.
  • Remove other filters (like wpautop) to lower interference even more.

I spent the spare time I had during that day and then after the after party from midnight to 5:30am the next morning looking through the code in the existing plugins and piecing together the best pieces of them. I liked how “Disable Visual Editor WYSIWYG” just grayed out and struckthrough the Visual tab instead of removing it directly. I liked how Raw HTML put things in the screen options space and also how they allowed for disabling the other filters.

Anyway, the plugin released that morning on GitHub and then later at the Dev Day to the WP repository. You can grab it here:

Don’t Break the Code WordPress Plugin

So far it allows admins to disable the Visual Tab just like we said. I improved on the DVE WYSIWYG plugin by disabling via Ajax for a better user experience (you don’t have to click update for it to take affect). And after trying to copy Raw HTML’s method of placing things in the screen options, decided to scratch that and just code it myself using some tutorials I found online.

It works nicely. I plan to add checkboxes for disabling other filters similar to Raw HTML and also want to include that “add a notice” functionality somehow. I was going to incorporate the syntax highlighting, but that works really well as a stand alone plugin. Chris’s code had some problems on my setup that I hope to look into and patch for him.

Let me know what you think of Don’t Break the Code. If you want to contribute, you can fork and patch via GitHub here.


Don’t Break The Code was last updated on November 10, 2011. Bookmark the permalink.

Disable the WordPress Admin Bar for Non-Admins Only

Here is a variation of some code I found on to disable the WP admin bar for non-admins only.

function yoast_hide_admin_bar_settings() 

Just copy and paste this code into your functions.php or another plugin/theme file that can add hooks. Save/upload and watch it work.

Let me know if you have any trouble using this.

Disable the WordPress Admin Bar for Non-Admins Only was last updated on June 2, 2011. Bookmark the permalink.

Duplicate comment detected; it looks as though you’ve already said that!

Not sure how long WordPress has been doing this, but there is a check for duplicate comments. If the same user/email posts the same exact comment on the same post, the user will get a message like:

Duplicate comment detected; it looks as though you’ve already said that!

This is great actually, and keeps people from submitting the same comment twice if they get impatient waiting for moderation or otherwise click that submit button twice.

As a blog owner and WordPress developer, there may be situations where you want to allow people to post the same comment. If you want to enable duplicate comments on your blog for some reason, you can use this code here. Just add it to your theme’s functions.php or put this in a .php in your plugins folder and enable it.

function enable_duplicate_comments_preprocess_comment($comment_data)
	//add some random content to comment to keep dupe checker from finding it
	$random = md5(time());	
	$comment_data['comment_content'] .= "disabledupes{" . $random . "}disabledupes";	
	return $comment_data;
add_filter('preprocess_comment', 'enable_duplicate_comments_preprocess_comment');

function enable_duplicate_comments_comment_post($comment_id)
	global $wpdb;
	//remove the random content
	$comment_content = $wpdb->get_var("SELECT comment_content FROM $wpdb->comments WHERE comment_ID = '$comment_id' LIMIT 1");	
	$comment_content = preg_replace("/disabledupes{.*}disabledupes/", "", $comment_content);
	$wpdb->query("UPDATE $wpdb->comments SET comment_content = '" . $wpdb->escape($comment_content) . "' WHERE comment_ID = '$comment_id' LIMIT 1");
		add your own dupe checker here if you want
add_action('comment_post', 'enable_duplicate_comments_comment_post');

For reference, here is the dupe check code in wp-includes/comment.php. A newer version should probably have a hook above and/or below to allow people to override the dupe checker more directly.

// Simple duplicate check
	// expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
	$dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND comment_approved != 'trash' AND ( comment_author = '$comment_author' ";
	if ( $comment_author_email )
		$dupe .= "OR comment_author_email = '$comment_author_email' ";
	$dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
	if ( $wpdb->get_var($dupe) ) {
		do_action( 'comment_duplicate_trigger', $commentdata );
		if ( defined('DOING_AJAX') )
			die( __('Duplicate comment detected; it looks as though you’ve already said that!') );

		wp_die( __('Duplicate comment detected; it looks as though you’ve already said that!') );
Duplicate comment detected; it looks as though you’ve already said that! was last updated on October 22, 2010. Bookmark the permalink.

SS-Downloads WordPress Plugin

Testing our new SS-Downloads plugin. It basically will require an email address before serving a specified file. Right now, I’m using a zip of the pre-release plugin for testing. I will update this to point to the latest version once it’s ready.

Should see a form or download link here.

[download file=””]

Future plans:

  • Option to require account creation (instead of just an email address). Done
  • Option to email file as attachment instead of showing a link. Done
  • Icons for files in template.


Q: My downloads are incomplete, corrupt, or otherwise not downloading… especially large files.
A: This may be caused by a low memory issue or some other issue with serving the file through the getfile.php script. You can configure the plugin to simply redirect to the chosen file rather than serving it through the script by editing /ss-downloads/includes/setup.php and setting the GETFILE_REDIRECT value to true. The file will have to be served in a public web folder, and 733t hackers will be able to see the actual URL of the file.
Note: I’ve changed the GETFILE_REDIRECT to default to true. But if you have the inverse problem (the download is working, but you want to make it more secure by avoiding the redirect — which savvy users might be able to watch to get the URL of the file) you can set that value to false.
Bob at has a good writeup of how to clear out the download stats for your files if you want to do that sort of thing.
SS-Downloads WordPress Plugin was last updated on July 21, 2010. Bookmark the permalink.

WordPress get_the_content_after_more() Function

In WordPress, if you want to get just the excerpt of a post, you can use the built-in functions the_excerpt or get_the_excerpt. And if you want all of the content, you can of course use the the_content or get_the_content functions. But what if you want to get everything BUT the excerpt?

The Code

Here is a function that will do that: get_the_content_after_more()

function get_the_content_after_more()
	$content = get_the_content();
	$moretag = preg_match("/</span>/", $content, $matches);
		$morespan = $matches[0];
		$morespan_pos = strpos($content, $morespan);
		$newcontent = substr($content, $morespan_pos + strlen($morespan), strlen($content) - strlen($morespan));
		$newcontent = apply_filters('the_content', $newcontent);
		return $newcontent;
		return "";

How to Use This

Notice that this is a “get_” version of the function. So you will get to echo the results or save them to a variable for future use. Just plop an echo get_the_content_after_more() into your LOOP and you’re good to go.

How it Works

The function works by getting the post content through “get_the_content” (and so will give you the content for the current post in your loop) and looking (preg_match) for the span tag that WordPress puts at the more break. (If older versions of WordPress don’t add this tag, this function won’t work. But this works in 2.9-3.0 at least.)

If a more tag is found, I create a variable $newcontent holding everything after the more tag. Then I run it through apply_filters to all of your plugins/etc that work on the_content will work on this.

If a post doesn’t have an excerpt (no excerpt or more tag in the post), the function returns an empty string.

The function could easily be called get_the_inverse_excerpt or get_the_content_after_excerpt or get_the_content_minus_excerpt. Let me know if you have a better idea for this… or tell me what you searched for to figure this out.

Why Would I Use This?

Kim was updating our portfolio page, which is really a list of WordPress posts. She wanted to style the “excerpt” differently from the rest of the content. Notice how the top section (“WineLog is…”) is in a gradient box on the WineLog portfolio item… and then the rest is styled as written in the post content. We used code like this:

When we decided to do this, I first checked if WordPress was adding some tag around the excerpt that we could piggy back on. Nope. All that is added is a span like at the point where the more break is. Then I looked for a buit-in function or some parameter of the_content that could be used to do this. No luck. (Let me know if there is a built-in way to do this.)

If I Were Updating WordPress…

… and it’s open source. So maybe I will. One could add a parameter to the_content/get_the_content functions to exclude the excerpt. The code would be largely the same, though they could look for the more tag itself since they won’t have that stripped out yet. That feels clunky to me. Let me know if you have better ideas.

WordPress get_the_content_after_more() Function was last updated on July 6, 2010. Bookmark the permalink.

On Ustream: WordPress Plugin to Capture Email Addresses in Exchange For a File Download

Update: No longer streaming. The plugin works great. Kim is going to make it pretty, then I’ll post to WordPress and do a right up.

I’m streaming live right now while I work on a WordPress plugin. Follow me at

I’ll be working on a plugin for a feature that we’ve done a million different ways: asking for a user’s email address in exchange for a link to a file download. A solid plugin for this will save us a lot of time. If it turns out well, I’ll put it in the WP plugin directory and link to it from here.

Here are the requirements/specs I have for this plugin:

  • Should use a short code of the form [filedownload: /path/to/file.txt] to define where the form should go and what file.
  • The form will submit to the current page, log the email entered, add a session flag.
  • If an email is in $_POST, the post/page will show the download link instead of the email form.
  • Files will be hidden behind a script to obscure the path to the file. The script will check for the session flag before returning the file.
  • Should use a template to make it easy to change the HTML/CSS for the form.
  • Should be easy to adjust the addEmail code to work with Constant Contact/etc.

That’s it. Please join me. Post questions to the chat. Again, if this code comes out clean, I hope to share it.

Enhanced by Zemanta
On Ustream: WordPress Plugin to Capture Email Addresses in Exchange For a File Download was last updated on June 30, 2010. Bookmark the permalink.

Unit of Measure PHP Class

For a recent project, we developed a php class that made it easier to work with units of measure. I was surprised that there wasn’t anything like this available out there, so we decided to open source the code once it was in a good state. That day has come.

We will be updating this code (and this blog post) over the next few days and likely down the road as well. But in the meantime, here is a link to the GitHub repository: phpUOM on GitHub.

(If this goes well, we’ll hopefully be open sourcing a bit more of our code in the future.)

Unit of Measure PHP Class was last updated on February 16, 2010. Bookmark the permalink.

Hidden 404 Errors with WordPress Plugin Pages

After a couple hours, I’ve tracked down and fixed a bug I was having with some of our WordPress plugins. I believe that there are a few people out there having the same problem. I think there may be another solution online, but it is one of those issues that is difficult to pare down to a good search query.

Anyway here is a solution for “404 issues with plugin pages” or “lynx shows a 404, but the page still loads”, or “Google Webtools says there is a 404, but I can get to the page”, or “setting status to 200:OK still results in 404”, or “I get a 404 in IE, but refreshing the page brings it up”, or “I get random 404 errors in IE”, or “I’m getting an HTTP/1.1 404 Not Found error but the page still loads”.

You may skip ahead to the Final Solution code, but it is probably a good idea to read everything below to make sure that you are indeed having the same issue I had… and that this will actually fix your problem.

The Context

I have some WordPress plguins (Stranger Products, Stranger Events) that generate pages outside of the core WordPress system (i.e. they are not “wordpress pages” in the WP DB, they are web pages generated by our plugin script). To serve these pages, I add a bunch of rules to the .htaccess file to redirect stuff like /products/1/ to a product info page.

Some gallery plugins or other plugins that generate new pages may have a similar setup/issue.

The Problem

While the mod rewrite works fine, and the page loads fine, WordPress doesn’t find a WP page or post for the query string and so sends a “HTTP/1.1 404 File Not Found” status in the header. Most web browsers will ignore this and show the content that comes after the header. It seems that IE will sometimes choke on this status, and other times show the page. Funny IE!

Google’s crawler however will not crawl that page and will let you know in a web toolkit report. Also, I noticed that the lynx command line browser for Linux would show the 404 error and then load the page.

The big issue here is that Google is not going to crawl our page.

The Fix

I spent a lot of time tracking down where in the WordPress code the 404 status is set. Ideally, there would be a plugin “hook” near this that we could use to prevent the 404 status from reaching the browser.

The function that makes the 404 decision is handle_404(), which can be found in the /wp-includes/classes.php file. Here is the code (for WordPress 2.8.4, similar for previous versions I looked at too):

function handle_404() {
	global $wp_query;
	if ( (0 == count($wp_query->posts)) && !is_404() && !is_search() && ( $this->did_permalink || (!empty($_SERVER['QUERY_STRING']) && (false === strpos($_SERVER['REQUEST_URI'], '?'))) ) ) {
		// Don't 404 for these queries if they matched an object.
		if ( ( is_tag() || is_category() || is_author() ) && $wp_query->get_queried_object() ) {
			if ( !is_404() )
				status_header( 200 );
		status_header( 404 );
	} elseif ( !is_404() ) {
		status_header( 200 );

This would be the ideal place to say, “Hey, don’t 404 this page”, but there is no hook in here. I tried setting the $wp->did_permalink flag to FALSE, which worked sometimes, but sometimes WordPress would write that back to TRUE after I reset it. And I’m not even sure what that flag is doing; so playing with it might cause some bugs elsewhere.

The next place to check is the status_header() function called by handle_404. This function is found in the /wp-includes/functions.php file. Here is the code:

function status_header( $header ) {
	$text = get_status_header_desc( $header );

	if ( empty( $text ) )
		return false;

	$protocol = $_SERVER["SERVER_PROTOCOL"];
	if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
		$protocol = 'HTTP/1.0';
	$status_header = "$protocol $header $text";
	if ( function_exists( 'apply_filters' ) )
		$status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );

	return @header( $status_header, true, $header );

Tada! This function uses the “status_header” hook/filter before updating the header. So we can create a function in our plugin to check the status for a 404 and then return false/NULL if we know that there really is a page to load. Here’s how I did it.

The Final Solution

In PHP code for my pages, I created a global variable called $isapage and set it to true. So at the very top of any page that is giving the 404 errors, add this code:

global $isapage;
$isapage = true;

Now I add the following function and filter to my plugin code:

//this function checks if we have set the $isapage variable, and if so prevents WP from sending a 404
function ssp_status_filter($s)
	global $isapage;
	if($isapage && strpos($s, "404"))
		return false;	//don't send the 404
		return $s;
add_filter('status_header', 'ssp_status_filter');

I hope this helps some people out there.

Feel free to critique this solution. Let me know if I missed something or if there are better ways to do this.

Feel free to post related issues. I may have found solutions to those along the way… or maybe a commenter can help you out.

Hidden 404 Errors with WordPress Plugin Pages was last updated on August 17, 2009. Bookmark the permalink.

Introducing TopWhatever

TopWhateverA new product from Stranger Studios. TopWhatever will change your life. From the about page:

TopWhatever helps you make decisions by walking you through the process of creating a “decision matrix”. Using the matrix, you can weigh your options against the criteria that are important to you.

Some decisions can get complicated quickly. The decisions you end up making can feel subjective rather than objective. TopWhatever helps you take things step by step. You end up with a decision that is sound, with the math to prove it.

The best way to understand how TopWhatever works is to view decisions that have already been made.

So check it out already. Use TopWhatever to make a decision that has been on your mind lately.

Introducing TopWhatever was last updated on February 5, 2009. Bookmark the permalink.

Interactive 8-Ball Facebook App

So we’ve jumped on the Facebook bandwagon a bit. You can now install the Interactive 8-Ball application to your Facebook profile.

Why would you want to install I8B on your Facebook profile?
I don’t know, but if you use Facebook as your homepage instead of iGoogle it’s nice to have I8B right there. We also update your profile and mini feed every time you ask a question through Facebook. Although this last bit can get tricky; we had a lady email us to take down a question she asked about a love prospect for fear of being had. (Which only gave us another idea for a Facebook app that we might share at some point.)

And What Happened?
I8B got a ton of traffic. In three days, we got 400 people to install the new application. Traffic to I8B trippled to 800 visits a day and then… leveled out. We actually lost 5-10 users today as people have started to uninstall the application. So growth is not exactly parabolic so far.

I guess we need something more to help the spread. (This blog post? A mention at TechCrunch? Maybe I’ll resubmit I8B to Emily Chang’s eHub.) It would be nice to have the 20,000 users that the other lame-o eight ball application on there has. Of course they got there first and so are high in the app directory and have the catchy URL at (ours is 😉

What’s next?
A WineLog app for Facebook, duh. The I8B stuff was kind of a primer for work on a WineLog application. And good thing too. It is nice to work out all of the kinks using a brand that we aren’t as invested in. This article helped me a bunch, but it also took a lot of hacking around to figure out what he meant by everything. The toughest part was fixing Facebook’s broken PHP4 client. Don’t even try messing with that unofficial one. If anyone needs help, shoot me an email or IM.

Anyway, a WineLog app would be fun. Again, I would rather just go to WineLog to see what my friends are drinking. But if you spend your day at Facebook, it’s sweet to get notifications on what people are logging. And it will hopefully introduce WineLog to some new folks. Cross your fingers.

UPDATE: Here are links to my versions of the facebook api scripts. Download them and rename them to .php. I hope to comment up the code when I get a chance, so you can see what I changed. But in the meantime, this might be a better starting place for you than Facebook’s version.


Download all of the above files, rename them to .php, and follow the tutorial instructions here (or do whatever you’re doing). The strange one at the bottom is a library to handle XML objects (PHP5 does this natively I suppose). Read here for more on simplexml44. Or here is the entire simplexml gzip file as I unzipped and installed it on my server.

Interactive 8-Ball Facebook App was last updated on June 28, 2007. Bookmark the permalink.

Easier Way to Implement Diggstyle

Way back, I wrote the tutorial on how to create a pagination scheme similar to the one that Digg uses. The code in the tutorial was meant to educate readers on how the algorithm works.

Meanwhile, I was using completely different code for my own projects. Typically I put all of the pagination code into a function (or PHP class), which makes it much easier to use in practice. Now I’ve made available a version of this function, which people should look to first if they want a quick implementation.

  • Download the PHP code for the function here: diggstyle_function.txt.
  • To use it make a function call like getPaginationString($page, $totalitems, $limit, $adjacents, $targetpage, $pagestring);.
  • $page is the current page number
  • $totalitems is the total number of items in the set. You usually get this from a SQL query.
  • $adjacents is the number of page links to put adjacent to the current page.
  • $targetpage is the URL you want to point to. e.g. index.php
  • $pagetext is the string used to append the page variable to the URL. e.g. ?page= or &p=
  • Use this style sheet.

Read the tutorial for more help and to see an example. For a real-live example, check out my Wine Log.

Also, Mis Algoritmos is at it again with a digg-style pagination plugin for Wordpress based on this code.

Easier Way to Implement Diggstyle was last updated on April 27, 2007. Bookmark the permalink.

Pagination Update

Earlier in the year, I wrote a tutorial on how to create pagination similar to Digg’s. The article focused on the basic algorithm for displaying the pagination, and there was definitely some opportunity for improvement in its implementation.

Well, the improvements are in. We have a modularized PHP version and a Perl version. See the updated pagination demo page for details.

Pagination Update was last updated on December 29, 2006. Bookmark the permalink.