Code


30
Aug 10

WordPress For iPhone/iPad NSXMLParserErrorDomain Error 64 Resolved

If you have a WordPress blog and an iPhone/iPad, then you most likely have the WordPress for iOS app.  If you don’t, you should.

Over the past couple of days, I have been receiving the following error when trying to add my blog to the iPhone app.

After scouring the internet, I found that this could be the result of a few issues.

  • Special characters in a post body that are not supported by NSXMLParser
  • Special characters in a comment
  • Invalid post or comment RSS
  • An error in a theme/plugin file

For me, this turned out to be an issue with the comments RSS feed.  I loaded it up in the browser and long behold, even the browser threw an error.  But what could be causing this?  Turns out, I had left a space in a plugin that I created.  This caused a space to be output at the beginning of the comments XML, causing it to error. Notice the space between ?> and <?php below.  (Face Palm)

After removing the space from this plugin, I loaded up WordPress for iPhone and it added my blog without a problem.

So, the take away from this is don’t output spaces when you create a plugin.

I hope this post has proven useful for you, I can’t imagine that I’m the only person with this issue ;)


27
Aug 10

Feedburner Anywhere Plugin Updated

I have updated my WordPress plugin Feedburner Anywhere. In case you are unfamiliar with it, it’s a plugin that allows you to output your Feedburner subscriber count anywhere on your blog.

The Problem: Since Google took over Feedburner, I feel that it has been quite unreliable. A few times a week, Feedburner would return 0 for your subscriber count. This was an issue with the plugin. If the return value was 0 when the plugin pulled and cached the feedburner data, you would look like you had no subscribers.

The Fix: I am now caching the values returned from Feedburner. If for any reason Feedburner returns a 0 subscriber count, the last known value (greater than 0) is used instead.

Download the updated plugin here

If you have any other suggestions for the plugin, please let me know.


8
Jun 10

Feedburner Anywhere Plugin Released

Image representing FeedBurner as depicted in C...

Image via CrunchBase

I have just released another WordPress plugin called Feedburner Anywhere.

What it does is allow you to display your RSS subscriber count anywhere on your blog.

You have the choice of using the built-in widget, embedding it in your posts/pages, or a combination of both.

Check out my sidebar for an example of usage.

Download Feedburner Anywhere at WordPress.org

Reblog this post [with Zemanta]

15
Apr 10

HECK YES C Macro, For When Something Is REALLY True

Quite possibly the most useful macro you will ever use.

#define HECK_YES true && true
 
// Usage
if(self.sleepy)
{
   self.needsCoffee = HECK_YES;
}

Now if only I could replace semi colons with exclamation points…


17
Mar 10

WordPress Coding: Programmatically Add Post Tags (and other meta info)


I was recently working on a script that imports from a custom blogging platform into WordPress and had some need to programmatically add post keywords.

The script to do this is actually quite simple and can be used to update any post attribute.

Here is the code:

// Create the post array
$post = array(
	'ID' => 5,
	'tags_input' => 'foo,bar,baz');		
 
// Update the post
wp_update_post($post);

This will assign the keywords “foo”, “bar”, and “baz” to the post with ID 5. This task seems trivial, however it’s very powerful when you think about automation. For example, you could write a script to scrape a google search for your target keyword and find related keywords for each of your posts automatically. Hrm… plugin idea?

Give it a shot. More info on available parameters can be found on WordPress’ site here

Here are some of the other fields that you are able to update this way:

defaults = array(
'post_status' => 'draft', 
'post_type' => 'post',
'post_author' => $user_ID,
'ping_status' => get_option('default_ping_status'), 
'post_parent' => 0,
'menu_order' => 0,
'to_ping' =>  '',
'pinged' => '',
'post_password' => '',
'guid' => '',
'post_content_filtered' => '',
'post_excerpt' => '',
'import_id' => 0);

Happy WPCoding!


12
Mar 10

WordPress Programming Tip: Enable Database Error Reporting For Custom Queries

So this one should seem pretty obvious, but it wasn’t apparent to me at first.  It was only after digging through the wp-db.php file that I discovered how to enable error reporting.

The Problem

As you may have discovered, the wp_query() function isn’t a “one size fit’s all” solution.  Often times, you may need to query the WordPress database using a custom MySQL query.  Especially  if you are using WordPress for anything other than a blog (ie freshapps.com).

When writing custom queries, it can often be frustrating if you make a mistake in the SQL syntax as WordPress will simply display no results.  For example:

$results = $wpdb->get_results("SELECT * FROM $wpdb->posts 
   WHERE post_title = 'foo bar baz");
print_r($results);
 
// Outputs Array ( )

Since we have made an error in our SQL statement (I didn’t add the second single quote), WordPress will suppress it and simply return an empty array. This is not very helpful for debugging.

The Solution

The solution is actually quite simple. The global $wpdb object has a property called show_errors. Setting this property to true will cause WordPress to output the SQL errors to the screen for a given query.

Here it is with our example above

// Enables Wordpress's DB Error reporting
$wpdb->show_errors = true;
 
$results = $wpdb->get_results("SELECT * FROM $wpdb->posts 
   WHERE post_title = 'foo bar baz");
print_r($results);
 
// Outputs 
// WordPress database error: [You have an error in your 
// SQL syntax; check the manual that corresponds to your 
// MySQL server version for the right syntax to use near 
// ''foo bar baz' at line 1]
// SELECT * FROM wp_posts WHERE post_title = 'foo bar baz

Now we know what went wrong with our query rather than just receiving empty results.

Let me know if you have any questions or comments.

Happy WPCoding!

Reblog this post [with Zemanta]

10
Mar 10

WordPress Plugin Development: Your First Plugin

Introduction

Creating plugins for WordPress seems like a daunting task at first, but the process is actually quite simple.  Wordpress’ APIs are very elegant and make plugin development a breeze.

The documentation for writing a plugin can be found here.  Make sure you bookmark it as you will be referring to the documentation quite a bit as you require more functionality.

WordPress Actions And Filters

When we talk about creating a plugin for WordPress, it usually refers to extending the functionality.  This could be something as simple as replacing all of the colon-parens with smilies or as complex as doing complete SEO optimization.  Whatever you want to create, chances are you will have to hook into a WordPress Action or Filter.

WordPress Filters are called any time there is data. They are essentially a chain of functions that will be called in order to work on the data in some way.  For example, when WordPress displays the content of your post, rather than it saying <?php echo $content; ?>, it calls the function <?php the_content(); ?>.  Calling this function will invoke the chain of functions to be applied to the content.

To hook a function into this chain, you will use the add_filter function of WordPress.

add_filter('the_content','myFunc');
 
function myFunc($content) {
   // Do Something to the content
   return $content;
}

In the code above our function called myFunc will be called every time the content is displayed in a WordPress post.  I will be explaining the is more detail later in this post.

With the knowlege of actions and filters behind you, you are ready to write your first plugin.

Setting Up

The plugin we will be creating is a Word Filter plugin. It could be useful on a blog with multiple authors as a swear word filter.  We will be replace all of the “naughty words”, which we define with a substitue.

The first thing you want to do is FTP into your Worpdress site and create the plugin folder.  The location of the folder should be as follows.

/wp-content/plugins/word_filter

Note that any time you create a plugin, it must go inside of the WordPress plugins folder.

Now create a file of the same name in this folder (word_filter.php). This will be the file that will hold all of our plugin code.  Just to reiterate, you should now have a file at this path:

/wp-content/plugins/word_filter/word_filter.php

Now we are ready to begin editing the file…

Adding the Meta Information

In order to identify your plugin (and give you credit for it), you must add the following information to the top of your plugin file.

/*
Plugin Name: Word Filter
Plugin URI: http://brandontreb.com/
Description: This plugin filters out certain words in a post.  Could be used as a swear word filter or just a global find and replace.
Version: 1.0
Author: Brandon Trebitowski
Author URI: http://brandontreb.com
*/

All of this meta information will be used to identify the plugin.  When the user goes to activate it, all of this info will be displayed in their admin panel.  It will look something like this:

Coding time…

Writing the Code

The first bit of code for our word filter is the array of words to be replaced. We will be using associative arrays where the key will be the words we are searching for and the values will be their replacements.

// Array of replacements
$search_array = array('idiot' => 'nice person', 'shutup' => 'please be quite', 'hate' => 'love');

As you can see, the word ‘idiot’ will be replaced with the words ‘nice person’, etc… You could do any amount of replacement here.

The next step is to write our function that will do the replacing. We will call this function word_filter. One thing you need to be aware of is the function must take exactly one argument. This is because we will be hooking into the the_content filter of WordPress. When our function gets called by the system, it will pass in the post content for every post that gets displayed. Here is what the function will look like.

function word_filter($content) 
{
	global $search_array;
 
	// Modify the content
	foreach($search_array as $find => $replace)
	{
		$content = str_replace($find,$replace,$content);
	}
 
	// Return the content
	return $content;
}

Pretty simple ehh? We loop over the $search_array and retrieve its keys and values. We then substitue the $find string with the $replace string in the post $content. Finally, we RETURN THE CONTENT. I emphasized that because it is very important. Since you are running this function in a chain of others, you must return the content so that the next function can process it. If you don’t the chain is broken and your posts won’t contain any content.

The last thing that must be done is we must hook into the the_content filter of WordPress. Again, this is how we get our function added to the chain. To do this, simply add the following line.

// Make sure our fn gets called before displaying the content
add_filter('the_content','word_filter');

This is just one of the many Filters that you are able to hook in to.

Putting it all together

When reading tutorial, I generally like to see the final source code in once place. So, here it is in all of it’s (very simple) glory.

/*
Plugin Name: Word Filter
Plugin URI: http://brandontreb.com/
Description: This plugin filters out certain words in a post.  Could be used as a swear word filter or just a global find and replace.
Version: 1.0
Author: Brandon Trebitowski
Author URI: http://brandontreb.com
*/
 
// Array of replacements
$search_array = array('idiot' => 'nice person', 'shutup' => 'please be quite', 'hate' => 'love');
 
// Make sure our fn gets called before displaying the content
add_filter('the_content','word_filter');
 
function word_filter($content) 
{
	global $search_array;
 
	// Modify the content
	foreach($search_array as $find => $replace)
	{
		$content = str_replace($find,$replace,$content);
	}
 
	// Return the content
	return $content;
}

*Note: I omitted the php wrapper tags because they were causing problems in the output. Make sure you add them back in.

There you have it! Your first WordPress plugin. In a later tutorial I will show you how to create an admin panel that will allow users to configure all of the search and replace words.

If you have any comments or questions, feel free to leave them in the comments section of this post.

You may also download the source for this example here.

Happy WPCoding!


4
Dec 09

Programming Tip Of The Day #2 – Difference Between i++ and ++i

To some, this should seem a bit obvious and if I am insulting your intelligence by discussing it, I am sorry.  But, one of the main reasons I want to discuss this topic is, I was asked this question in a job interview for Lockheed Martin.

What is the difference between i++ and ++i?

The answer is actually quite simple.

i++ first evaluates the value of i and then increments it

++i increments the value of i and then evaluates it

Here is a brief example to demonstrate what I mean.

// Example: i++ 
$i = 5;
echo "The value of i is " . $i++ ;
// Output "The value of i is 5"
// i = 6
 
// Example: ++i 
$i = 5;
echo "The value of i is " . ++$i;
// Output "The value of i is 6"
// i = 6

So, now if you are ever asked about this in an interview, you will have a response.

Happy programming!


3
Dec 09

Programming Tip Of The Day #1 – Ternary Operator

So, I though I’d start this series called Programming Tip Of The Day to write about useful things I come across in programming.  Both to educate my readers and as a personal archive of ideas and tips.

I will kick it off today with a quick rant about the ternary operator.  I <3 the ternary operator.  It’s quick, efficient and saves a lot of ugly code.

For those of you who don’t know, the ternary operator is made up of 3 elements: The condition and two results.  It is of the form:

(condition) ? (result if true) : (result if false);

This is much nicer than an if statement.  So here is a brief example about how a ternary operator can replace an if-statement.

if-statement

if(isSnowing) {
	iMustBe = "cold";
} else {
	iMustBe = "warm";
}

Same thing using ternary

iMustBe = isSnowing ? "cold" : "warm";

That is so much easier to read (IMHO). You can even do clever things in printing. Here is a small example in PHP for using the ternary operator when doing an echo.

<?php
  echo "I am a ".((height > 72) ? "tall" : "short")." person!";
?>

Most languages support the ternary operator. Check out this wiki page if you want more info.

Happy programming!


27
Nov 09

Increase Your Twitter Following Using Your WordPress Blog

twitter_bird

Download TwitPop Now

TwitPop is a WordPress plugin I wrote with one goal…To make you more popular on Twitter. There are sites that spring up from time to time claiming to get you more followers on Twitter if you follow X amount of people on the follow train. Well, now you can create your own Twitter train on your wordpress blog and really get more followers.

The best part is, you add your username in the admin panel and EVERYONE FOLLOWS YOU! Think of the possibilities… You could be a Twitlebrity.

To add to the excitement, everyone that uses your TwitPop plugin will Tweet a link back to your blog. This promotes your blog as well as your Twitter account. Check out how TwitPop works below.

Instructions

Log in to your Twitter account below.  You will automatically follow the people that have visited this page before you (no more than 20).

Then, your Twitter username will be added to the list and you will be followed by the next 20 people to use this plugin.

[twitpop]

Download TwitPop Now