brandontreb.com Tips And Resources For Software Consultants

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’ => ,
‘menu_order’ => ,
‘to_ping’ =>,
‘pinged’ =>,
‘post_password’ =>,
‘guid’ =>,
‘post_content_filtered’ =>,
‘post_excerpt’ =>,
‘import_id’ => );

Happy WPCoding!

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]

Emacs For OSX Is Out!

For all you Vi using, Emacs haters out there, I will fight you!

The iPad Is Out And It Sounds Like iPod While Plugging Your Nose

Watch Out Apple, The Kindle Dev Kit Is Almost Live

With the success of the Apple App Store, it seems that everyone is wanting a piece of the pie.

Amazon is now looking to throw their hat into the ring and is releasing their own dev kit for their ever so popular Kindle.

http://www.amazon.com/gp/feature.html/?ie=UTF8&docId=1000476231

It appears that big name game developers Electronic Arts is also getting involved (WTH?!?!)

This just seems like it will be an epic fail. Who really wants to play video games on their Kindle? Maybe they can port Kirby’s Dreamland from the original Game Boy :) .

Reblog this post [with Zemanta]

Code Monkey Music Video

Watching this video makes me appreciate the fact that I work from home.



Hacking Redbox – How To Get Free DVDs

Red Box, Video Rental Automat, found in a Wal-…

Image via Wikipedia

I was at Wally-World the other day getting a movie from RedBox with my wife when I noticed some guy enter in a code into the machine. The code was BREAKROOM. After watching him for a moment, I realized this code entitled him a free DVD rental.

Now, RedBox is pretty stinking cheap ($1.50/night), but if you’re an avid movie watcher, this really adds up.

So, I did some searching on the Google machine and sure enough, there are new RedBox codes that go into circulation every day. Each one giving you a free DVD.

The site that offers the RedBox codes is http://www.insideredbox.com/redbox-codes/

Users submit the codes and update the site with the last time they were used. That way, you always know which codes are currently working.

You simply need to enter the coupon code from the main screen or just before checkout at your local Redbox kiosk. When you do, you will receive a one-day free rental. Any additional days you keep the movie will be charged at the usual $1.50/day.

Update: @diemer on Twitter pointed out to me that inside Redbox also has an iPhone app. The link for the app is http://itunes.apple.com/us/app/inside-redbox-pro/id306217360?mt=8

I may actually cancel my Netflix account now…

Reblog this post [with Zemanta]

Great List Of Algorithm Programming Tutorials

Recently TopCoder.com posted a list of algorithm tutorials from some of their “top coders”.

The tutorials are very comprehensive and pretty much sum my undergraduate computer science degree up in one page :) This page is a great resource for anyone that does any amount of coding…

Some of the tutorials include:

  • Greedy algorithms
  • Various sort and search techniques
  • Data structures
  • Graph theory

Here is the link to the Top Coder Tutorials:

http://www.topcoder.com/tc?d1=tutorials&d2=alg_index&module=Static

Reblog this post [with Zemanta]

XCode Shortcut

When in XCode on a MacBook Pro, doing a 3-finger swipe up will switch between the .h and .m files.

⌘-option-up will do the same thing

Productivity++

Reblog this post [with Zemanta]

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!

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

<code class=’c’>if(isSnowing) {
    iMustBe = "cold";
} else {
    iMustBe = "warm";
}</code>

Same thing using ternary

<code class=’c’>iMustBe = isSnowing ? "cold" : "warm";</code>

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.

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

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

Happy programming!

Mac OSX Tip: Hotkey To Hide/Show the Dock

While mashing the keyboard (as I often do when debuggin poorly written outsourced code), I stumbled upon a very useful OSX hotkey.

⌘-option-d

This command will cause the Dock to go in and out of auto-hide mode.

Not the most useful, but very helpful to geeks like me who rearrange their desktop every day.

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

First learn computer science and all the theory. Next develop a programming style. Then forget all that and just hack.

George Carrette [1990].

PHP Class To Interface With Many URL Shortening Services

With the explosion of Twitter and such services, the need to have long URLs shortened has drastically increased. Naturally, many services to shorten URLs have sprung up as well.

Most of these services (that are worth using), have some sort of API that will allow developers to send a long URL to them, have it shortened and then returned. This type of service allows other developers to write applications that have the ability to shorten URLs right inside of them.

Recently, I had to write a PHP class to work with URL shorteners. So, I made it support multiple shortening services and have decided to share it with you.

The class is called URLShortener.class.php and it supports the following shortening services:

  • j.mp (bit.ly)
  • tr.im
  • TinyURL
  • is.gd
  • u.nu
  • Linkyy
  • Your own custom shortening service

Here are some examples of how to use the class in your own applications:

<code class=’php’><?php
     /* Basic: */
     $s = new URLShortener(‘tr.im’);
     echo $s->shorten("http://brandontreb.com");
     
     /* Using API Key and Login */
     $s = new URLShortener(‘j.mp’);
     $s->login = ‘brandontreb’;
     $s->APIKey = ‘R_2a413ebd15254a72b500ec2ce83f982d’;
     echo $s->shorten("http://brandontreb.com");
     
     /* Custom URL */
     // Just make sure you put %s and it will be 
     // replaced with the long URL
     $s = new URLShortener(‘custom’,
        ‘http://b1t.me/api/shorten.xml/%s’);
     echo $s->shorten("http://brandontreb.com",false);
?></code>

You may download my URLShortener PHP class here.

Feel free to leave any questions or comments in the comments section.

Programming

99% of students that were in my CS degree program

99% of students that were in my CS degree program

Image taken from abtrusegoose

$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!

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.

Object-oriented programming is an exceptionally bad idea which could only have originated in California.

Edsger Dijkstra

Was Jesus A Real Person? Great Article On Digg Today

The culture of Digg is generally very liberal (to say the least). That is why I was very surprised to find one of the top stories of the day entitled ”Was Jesus A Real Person?”. Obviously, the comments section of the article was full of people arguing about the matter.

I found the article to be quite well written and made a stellar case for the existence of Jesus. So whether you are a believer or not, you should check it out. Take a look for yourself and let me know what you think.

Article Link

New Alice in Wonderland Poster Is Sweet

Very stoked for this movie. Photo source ign

TweetPress Now Supported By Twittelator Pro

For many of you this is old new. But since it’s latest release, Twittelator Pro has supported TweetPress as one of the options for Photo Posting. Here are the steps to configure Twittelator Pro:

  1. First, make sure you have TweetPress installed on your WordPress blog by following the installation instructions here
  2. Tap the Settings tab
  3. Select WordPress from the dropdown under Choose Photo Service
  4. ** **Tap **Other Services **(you should see the WordPress logo) and then tap **Tweetpress for iPhone **
  5. ** Enter in your WordPress credentials
    1. Site Link: The URL of the hompage of your wordpress blog
    2. Username – your wordpress username
    3. Password – your wordpress password
<img class="alignnone size-full wp-image-364" src="http://brandontreb.com/wp-content/uploads/2009/10/p_480_320_B39E129D-6327-41C5-94DE-474D13974ED7.jpeg" alt="" width="200" height="300" /></li> 

  * Tap Done</ol> 

You should now be good to go. Any time you choose to post a photo to your Twitter stream, it will use your TweetPress plugin on your WordPress blog. Please let me know if you encounter any issues or have suggestions for Tweetpress.

I have been in contact with developers of other popular Twitter clients and hope to get Tweetpress integrated in them soon.

[][2]

<div style="">
  <a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="TweetPress Now Supported By Twittelator Pro" data-url="http://brandontreb.com/tweetpress-now-supported-by-twittelator-pro"  data-via="brandontreb" data-related="brandontreb:">Tweet</a>
</div>

Post Photos To Twitter From Your WordPress Blog With TweetPress

twit

That’s right. With the latest release of TweetPress (version 1.1.1), you can post photos directly to Twitter from your WordPress blog’s gallery page. Here are the steps to do it.

  1. Navigate to the TweetPress admin Settings > TweetPress
  2. Enter your Twitter username and password
  3. Press the Save Twitter Settings button
    1. TweetPress will verify your username and password with Twitter
    2. If they are incorrect, it will let you know and you must re enter them
  4. Navigate to your gallery page
  5. You should now see a form that has a text box and an upload button
  6. Click browse to find an image on your computer to post
  7. Enter your Tweet in the box
  8. Click Post

It’s very quick and easy. If you have any suggestions for TweetPress please contact me, or leave comments in this post.

TweetPress coming soon to a Twitter Client Near You

TweetPress is the WordPress plugin that gives you total control and ownership of the photos you post to Twitter, sending your traffic back to your own blog, instead of a third party site

I just finished development of this WordPress plugin and Andrew Stone of Twittelator has integrated it into his latest version of Twittelator Pro. As of this post, that version is still in review, so you will have to wait until it is approved to make use of TweetPress.

I have some other very big plans for future releases of TweetPress and if you have any feature requests, feel free to drop me a line. I will do a post as soon as the latest version of Twittelator is approved and demo how it integrates with TweetPress.

iPhone In Action Book

iphone-in-action

A couple months ago, I was asked by someone on Twitter if they could “introduce me to someone”. I found this question a little odd so I responded with “like a girl or a developer?”. I often tweet about my wife, so I was hoping he was not referring to a girl. He replied with “no, someone at Manning Publishing, they are looking for an author for their book iPhone In Action”. So, I was put in contact with Manning and they eventually offered me the position as one of the authors on the book iPhone In Action.

iPhone In Action is a book (that is already out) and details how to program for the webkit as well as the native iPhone OS. I will be removing the webkit chapters, updating some of the dated chapters, and writing about 6 new chapters related to OS 3.0.

I will be posting about the book and my progress along the way (don’t worry I won’t stop my random tutorials about Twitter, WordPress, etc…). Just wanted to share that and say go out and buy the book (in December when I am finished and will get the commission :) ).

Happy Coding!