Posts Tagged: coding


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!


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!


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!


13
Nov 09

$13 Dollar Discount On Programming Books From Manning Publishing

manning-logo

The publishing that I’m writing the book for is having a huge Friday the 13th sale.  They are offering a $13 discount on all of their books.  For those of you who don’t know, Manning publishes all of the “In Action” books.

All you have to do is go to the site and enter the coupon code:

fri13

when checking out and you will get the discount.  Although my book iPhone In Action 2nd Edition hasn’t been released yet, Manning has some other killer programming books for sale.

So be sure to check it out!


12
Nov 09

Money You Might Be Missing Out On – LinkShare API Integration

logo

As you may know, I am the developer of the site FreshApps.com.  One thing we had been doing to make some extra money is to use Linkshare to be an affiliate for Apple.

If you don’t know, Linkshare is a service that allows you to become an affiliate of thousands of companies.  You simply select one of the companies products, get the linkshare link, and put the link on your site.  Now, every time someone clicks that link and makes a purchase, you will get a percentage of the revenue.

The Problem

The only problem was, we have thousands of apps and converting the links manually seemed like such a daunting process. So, as you can imagine we converted around 10 links and never looked at it again.

Well, earlier today, the designer of the site JJ Mancini, asked me to check and see if linkshare had an API.  I checked it out and sure enough, they did and it was no more complex than interfacing with a URL shortening service.  So, I wrote the script and within minutes, all of our downloads links were converted into something that can now make us some revenue.

The Solution

Now that I have created the script, I figured I would pretty it up and share it with you.  Keep in mind, the script is stupid easy, so if I am insulting your intelligence by showing it, I apologize.

<?php
	/* linkshare.php */
 
	// Your linkshare API token
	$token = "89705XXXXd11ab28ae548bXXXX4ad6475279faXXXX65da0ec8ed77XXXXeb067";
	// Apples Merchant ID
	$mid   = "13508";
 
	$linkShareLinks = array();	
 
	// I assume links in an array of links to the app store
	foreach($links as $link) {
		$linkShareURL = "http://feed.linksynergy.com/createcustomlink.shtml?".
			"token=$token&mid=$mid&murl=$link&mt=8&buylink=yes";
		$linkShareReturn = file_get_contents($linkShareURL);
 
		if(stristr($linkShareReturn, "click.linksynergy.com")) {
			array_push($linkShareLinks,$linkShareReturn);
		} 
	}
 
	print_r($linkShareLinks);
?>

And that’s it! The variable $linkShareLinks will now contain all of the App Store links converted to your account’s linkshare url. If you have any site with that contains ads for apps in the app store (review site, developer blog, etc…), you would be crazy not to integrate with linkshare.

Give it a try, and feel free to ask questions in the comments section.


11
Nov 09

iPhone In Action Book – Free Chapter Downloads

Trebitowski-iPhone-2E-1-1

iPhone In Action 2nd Edition

Manning Publishing has started their MEAP (Manning Early Access Program) for the book I am working on.  What this means for you is FREE DOWNLOADS.  There is currently only one chapter available, but there will be more as the book progresses.

The chapter currently available is about audio recording and playback.  It goes into detail about the AVAudio frameworks as well as the MPMediaPlayer.

So be sure to check it out and feedback on the chapter is GREATLY appreciated.

Link to MEAP