March, 2010


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!