Top WordPress hacks of 2009

by Jean. 68 Comments -

2009 has been a very prolific year for WordPress hacks. In this article, I’ll show you the most useful hacks I came across during the whole year. Enjoy!

Monetizing your old blog posts

Let’s start this post with a nice hack dedicated to help you make more money online, initially published on my other blog Cats Who Blog.
If you don’t want to bore your loyal readers but still want to earn some bucks, what about monetizing only your old blog posts instead? This code will add some advertisements only if the post is more than 15 days old.

The following function has to be pasted in your functions.php. If you are using the Thesis theme this file is named custom_functions.php.

function is_old_post($post_id=null){
   $days = 15;
   global $wp_query;
   if(is_single() || is_page()) {
      if(!$post_id) {
         $post_id = $wp_query->post->ID;
      }
      $current_date = time();
      $offset = $days *60*60*24;
      $post_id = get_post($post_id);
      $post_date = mysql2date('U',$post_id->post_date);
      $cunning_math = $post_date + $offset;
      $test = $current_date - $cunning_math;
      if($test > 0){
         $return = true;
      }else{
         $return = false;
      }
   }else{
      $return = false;
   }
   return $return;
}

Once you’ve successfully inserted the code in your function.php file, you are now ready to call the functions in your single.php template as shown below:

<?php if(is_old_post()){ ?>
INSERT AD CODE HERE
<?php } ?>

Source : http://www.catswhoblog.com/how-to-monetize-your-old-blog-posts

Display your posts word count

Many people asked me about being able to get the post word count and display it. It is definitely easier to do than you may think at first.
Simply open your functions.php file and paste this function in it:

function wcount(){
    ob_start();
    the_content();
    $content = ob_get_clean();
    return sizeof(explode(" ", $content));
}

Once finished, you can call the function within the loop to get the number of words for the current post:

<?php echo wcount(); ?>

Source : http://www.wprecipes.com/wordpress-function-to-display-your-posts-words-count

Detect the visitor browser within WordPress

One of my favorite WordPress hacks of the year is definitely this one, which is incredibly useful. While conditional comments are a great way to target specific browsers, WordPress has one detection function that you can use to make your web developer life easier.

<?php
add_filter('body_class','browser_body_class');
function browser_body_class($classes) {
	global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;

	if($is_lynx) $classes[] = 'lynx';
	elseif($is_gecko) $classes[] = 'gecko';
	elseif($is_opera) $classes[] = 'opera';
	elseif($is_NS4) $classes[] = 'ns4';
	elseif($is_safari) $classes[] = 'safari';
	elseif($is_chrome) $classes[] = 'chrome';
	elseif($is_IE) $classes[] = 'ie';
	else $classes[] = 'unknown';

	if($is_iphone) $classes[] = 'iphone';
	return $classes;
}
?>

The final result will look something like this, if you view the source code of your page:

<body class="home blog logged-in safari">

Source : http://www.nathanrice.net/blog/browser-detection-and-the-body_class-function/

Get short urls for social bookmarking

With the rise of Twitter and its 140 characters limit, bloggers have to use short urls to fully take advantage of this new social media phenomenon.
Lots of quality url shorteners are available, but this trick will create a shorter version of your urls automatically, making you save time and hassle.
Paste the following code on your single.php file:

<?php echo get_bloginfo('url')."/?p=".$post->ID; ?>

It will output a url similar to:

http://www.catswhocode.com/?p=54

Source : http://www.wprecipes.com/how-to-get-short-urls-for-social-bookmarking

Get the first image from the post and display it

This hack has been a favorite of WpRecipes during the year 2009. And I understand that because this hack is very useful, especially for “magazine” themes: It allows you to automatically get the first image from the current post, and display it.

The first thing to do is to paste the function below on your functions.php file.

function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  if(empty($first_img)){ //Defines a default image
    $first_img = "/images/default.jpg";
  }
  return $first_img;
}

Once finished, you can simply call the function within the loop to display the first image from the post:

<?php echo catch_that_image() ?>

Source : http://www.wprecipes.com/how-to-get-the-first-image-from-the-post-and-display-it

Use SSL on wp-admin directory

On the internet, security is always a concern. If your hosting provider supports it (Wp WebHost and HostGator does) you should definitely enable SSL support.
SSL is a cryptographic protocol that provide security and data integrity for communications over TCP/IP networks such as the Internet. TLS and SSL encrypt the segments of network connections at the Transport Layer end-to-end.
Open the wp-config.php file and paste the following:

define('FORCE_SSL_ADMIN', true);

Next, save the file, and you’re done!
Source : http://www.wprecipes.com/how-to-force-using-ssl-on-wp-admin-directory

Enhancing the search function

WordPress has a built-in “search” function which isn’t bad, but should have been better. For example, one of the things that could enhance it is to highlight the search results.
To do so, open your search.php file and insert this code:

<?php
	$title = get_the_title();
	$keys= explode(" ",$s);
	$title = preg_replace('/('.implode('|', $keys) .')/iu',
		'<strong class="search-excerpt">\0</strong>',
		$title);
?>

Then, you’ll have to define a style for the search-excerpt CSS class. Just open style.css and paste:

strong.search-excerpt { background: yellow; }

Source : http://yoast.com/wordpress-search/

Post on your WordPress blog using PHP

Many of you have enjoyed my “Awesome things to do with cURL” article, published in June. One of the most interesting snippets from that article is showing how to post articles on your WordPress blog, using PHP and cURL.

Here is the function. This code is not made for being used within WordPress, so don’t paste it on your functions.php file (or any other).

Please note that you must activate the XMLRPC posting option in your WordPress blog. If this option isn’t activated, the code will not be able to insert anything into your blog database. Another thing, make sure the XMLRPC functions are activated on your php.ini file.

function wpPostXMLRPC($title, $body, $rpcurl, $username, $password, $category, $keywords='', $encoding='UTF-8') {
    $title = htmlentities($title,ENT_NOQUOTES,$encoding);
    $keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);

    $content = array(
        'title'=>$title,
        'description'=>$body,
        'mt_allow_comments'=>0,  // 1 to allow comments
        'mt_allow_pings'=>0,  // 1 to allow trackbacks
        'post_type'=>'post',
        'mt_keywords'=>$keywords,
        'categories'=>array($category)
    );
    $params = array(0,$username,$password,$content,true);
    $request = xmlrpc_encode_request('metaWeblog.newPost',$params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    curl_setopt($ch, CURLOPT_URL, $rpcurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    $results = curl_exec($ch);
    curl_close($ch);
    return $results;
?>

Source : http://www.wprecipes.com/post-on-your-wordpress-blog-using-php

Rewrite author name with custom field

If you often invite other bloggers to post on your blog, this tip is a must have. It simply allows you to create a custom field with the name of the guest author, and it will overwrite the the_author(); functions.
Simply paste the following code on your single.php and page.php, where you want the author name to be displayed.

<?php $author = get_post_meta($post->ID, "guest-author", true);
if ($author != "") {
    echo $author;
} else {
    the_author();
}  ?>

Source : http://www.wprecipes.com/rewrite-author-name-with-custom-field

Detect mobile visitors on your WordPress blog

Mobile devices as such the Blackberry or iPhone are more and more popular everyday, and this is why you definitely should take those readers in consideration by offering them a mobile version of your blog.
This hack is definitely easy to implement, thanks to Jeff Starr and Chris Coyier, the author of the excellent “Digging into WordPress” book.

To achieve this recipe, you first have to get the code from detectmobilebrowsers.mobi and upload it to your theme directory.

Then, simply open your header.php file and place the following at the top of the file. Don’t forget to edit line 5 according to the page where you’d like to redirect mobile users.

include('mobile_device_detect.php');
$mobile = mobile_device_detect();

if ($mobile==true) {
  header( 'Location: http://your-website.com/?theme=Your_Mobile_Theme' ) ;
}

Source : http://digwp.com/2009/12/redirect-mobile-users-to-mobile-theme/

By the way, if you’d like to win a premium WordPress theme, check out the contest I’m currently running on Cats Who Blog.

  • http://since1985.de Gerrit

    nice collection – keep up the great work and have a wondeful time!

  • Pingback: uberVU - social comments

  • Pingback: Top WordPress hacks of 2009 | WordPress News

  • Pingback: Top WordPress hacks of 2009 | Webs Developer

  • http://www.cigarinspector.com Denis

    Nice list.
    I would add another one for monetizing – display ads only to visitors from search engines. Not sure where I got the code from, perhaps from here :D

  • http://www.animhut.com/ sriganesh

    nice hacks , by the way i have written a tutorial on how to add Twitter ID in your comment box. it for eg: you have seen in colourburned blog. can you add here :D

  • http://www.wprecipes.com Jean-Baptiste Jung

    @Denis : I guess you had it from WpRecipes or CatsWhoBlog.com :)

  • http://ineeddiscipline.com Steven Richardson

    The monetizing old posts is something that I could do with implementing on my blog. I ghet a few complaints about ads, hopefully this can help. :)

  • http://www.online-blogger.net Indrek

    Great list. Had read quite a few of them. Nice to freshen my memory.
    Thanks

  • Chakib

    nice collection , but … hum ! is that all for 2009 ????

  • Pingback: === popurls.com === popular today

  • http://www.314media.com 314media

    These look great thanks!! Thanks for the rundown!

  • http://www.revenuerobot.com Revenue Robot

    great collection! i’ve been looking for the word count hack… Thanks!

  • http://www.jennamolby.com Jenna Molby

    Great list, thanks for sharing!

  • http://www.twitter.com/robertoalvarado/ Roberto Alvarado

    Very Nice, do you hay more of the hacks? They are very interesting!

  • http://positiveclicks.com Positron

    Thanks for this great list!

  • http://perishablepress.com/ Jeff Starr

    Awesome collection of hacks! Thank you for collecting them all into one convenient post. The browser-detection/body-class filter is by far my favorite :)

  • Pingback: CatsWhoCode.com: Top WordPress hacks of 2009 | Webs Developer

  • Jancok

    Cool…

  • http://www.redesignyourbiz.com/ Maverick

    These hacks are just stunning. I am really impressed by WordPress. I will surely play around a lot with WP.

    Thanks for this lovely post.

  • http://www.wprecipes.com Jean-Baptiste Jung

    @Jeff Starr : I have to agree that the browser detection class is one of my favorites…The “Get 1st image from the post and display it” has been a real life saver for me during the whole year!

  • Pingback: Top WordPress hacks of 2009 | Lively Web Tuts

  • http://johan.notitia.nl/ Johan de Jong

    A small addition to “Post on your WordPress blog using PHP” (or any other cURL related snippet):
    When cURL isn’t enabled at your host you can use an alternative method which uses the PHP function fopen()

    function send($url, $data) {
    $connection = @curl_init($url);
    if($connection) { // check if there is a cURL connection
    $data = http_build_query($data);
    curl_setopt($connection, CURLOPT_POST, true);
    curl_setopt($connection, CURLOPT_POSTFIELDS, $data);
    curl_setopt($connection, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($connection);
    $status = curl_getinfo($connection, CURLINFO_HTTP_CODE);
    curl_close($connection);
    } else {
    $params = array(
    ‘http’ => array(
    ‘method’ => ‘POST’,
    ‘content’ => $data
    )
    );
    $ctx = stream_context_create($params);
    $connection = @fopen($url, ‘rb’, false, $ctx);
    if(!$connection) $status = ’400′;
    else {
    $result = @stream_get_contents($connection);
    if($result === false) $status = ’400′;
    else $status = ’200′;
    }
    }
    return array(‘result’ => $result, ‘status’ => $status);
    }

    This function requires PHP 4.3 and no additional libraries.

  • Hirsute

    About the “Display your posts word count” hack. What about the “str_word_count()” function ? much easier than exploding a string !

  • http://www.wprecipes.com Jean-Baptiste Jung

    @Johan de Jong : Thanks a lot for this code! Very useful indeed!

  • http://www.web-design-talk.co.uk Rob

    Nice list here. Surely through getting a word count via exploding your entire post is slow.

  • http://anarm.net/blog/ Anarm

    thanks for sharing the great lists..

  • http://www.designboy.co.uk DesignBoy

    Great hack’s thanks!

  • http://www.threestyles.com Shane Jeffers

    Great List Jean. I might end up using the first image hack somewhere.

  • http://www.nationwideworktops.com/corian-worktops-uk/home/ Corian

    Thanks very much for this list. Definitely going to be using a few of these

  • http://supercarly.co.uk/ Carly

    Fantastic hacks!! Going to use the search one, it’s something I’ve always wanted my blog to do!

  • http://www.bennecontentos.nl Rutje

    PHP has a word count function str_word_count, this might give better and faster results that exploding a sting.

    php.net/manual/en/function.str-word-count.php

  • http://www.magicsolv.com Mark

    Great job !! I impressed to see. this is a nice post it worth to learn some more thing abut programing…really Many people may be able to count post words and display it. you made It 100% easier ..keep it up celeb christmas

  • http://blog.psax.de Ben

    Thanks for this great compilation! Helped me a lot!

  • http://www.w2point.com Can

    Great hacks, thank you!

  • Pingback: Daily Digest for December 23rd « Alex Bilbie

  • http://alexshapovalov.com Alex Shapovalov

    Excellent article, a few interesting tips that I am going to employ on my blog very shortly. I wanted to thank you guys for delivering quality content, definitely a refreshing way to blog( Fewer posts, but very high quality posts). Keep up the great work, Cats :)

  • http://www.larp64.com Jose Sogiros

    The “Rewrite author name with custom field” is a nice one. Easy and clean and very welcome.

    Keep it up!

  • http://theconstructor.org gopal

    nice collection.. thanks.. can u tell me how to get defualt first picture in arras theme of wordpress..

  • http://krisroxas.com Kris Roxas

    Wow, I didn’t even know WordPress had so many hacks =) I think I may try a few of those out, and go look for some more. There are probably a lot of things I could do to my blog without knowing it.

    Kris Roxas

  • http://www.shendapack.com toms

    i’m impressed very great share you have
    thanks a lot

  • http://www.pixelelement.com/ Carlos B

    Awesome compilation of tips!!!

    Thanks

  • http://www.bigtunainteractive.com/services/web-design/ Adam Hermsdorfer

    Very nice list. I don’t see the value of showing the word count in your posts. Can you give an example site that uses that feature?

  • http://www.techcats.net/ Rajesh Kanuri @ TechCats

    nice collection and beautiful round up.. thanks for the collection..

  • http://www.backon-online.com Flick

    I really like the snippet which highlights the keyword in the search result and the one for replacing the author field with the value in the_author! Thanks :)

  • Pingback: L’hebdo WordPress | WordPress Francophone

  • http://www.a2sm.com Seth Goldsein

    Great post and great hacks thanks for sharing.

  • http://labs.dariux.com Dario Gutierrez

    Excellent hacks, I like everyone.

  • Pingback: Best Of The Best In 2009 | Creative Magazine

  • http://blog.djorgi.de dan djorgi

    nice list. thanks!

  • http://www.1800pools.com/swimming_pool_chemicals.html Todd D

    Awesome list, thanks.. I will implement mobile visitors and enhanced search on my blog.. Thanks Jean…

  • http://www.laketahoehotelreservations.org/ Jenny Johnson

    I like the collection. Thanks for sharing this kind of different stuff.

  • http://tutorijali.hdonweb.com/ Ivan MiÅ¡ić

    Great hacks, thx for posting :-)

  • Philippe Dionne

    Great post!

    I think a web designer should always try to use hacks instead of plugins, so the theme comes packaged.

  • Pingback: Mes favoris du 11-01-10 au 13-01-10 » Gilles Toubiana

  • http://www.yourdesktopcomputer.com.au rod pallain

    Nice collection and beautiful round up.. thanks for the collection..

  • http://www.yourdesktopcomputer.com.au rod pallain

    Nice collection and beautiful round up…Thanks for sharing this kind of different stuff.

  • Pingback: Wordpress Hacks & Tricks – A grande lista  | 2.0 Webmania

  • Pingback: This Week’s Favourites – January 22nd 2010

  • http://www.codesquid.co.uk Codesquid

    These are pretty useful! Thanks for the list!

  • http://snilesh.com neel

    Excellent collection of all the wordpress hacks. love too see more hacks in future.

  • http://easyfitnesswebsites.com/blog Tony M

    Awesome tips as usual. I had a question as to your detecting browsers tip, why exactly? With things like Google Analytics and Statpress, why would this be necessary?

  • Pingback: Serious Monday Roundup #23 « TOURISM MARKET

  • Pingback: 2009 : L’année et la décennie en 30 liens | Web News - Web Marketing

  • http://www.gonzoblog.nl Gonzo the Great

    Hi Jean-Baptiste,

    The hack ‘Get the first image from the post and display it’ doesn’t always have to work on all off the wordpress-themes. As it didn’t work on the gonzoblog.nl …

    But I figured out what the problem is. In some themes this hack just shows the URL of your 1st image and not the actual picture! Change the code for your (home)page to:
    <img src="<?php echo catch_that_image() ?>" alt="" class="th" />

    Now you’ve got a picture there! In the gonzoblog my first picture is a divider/spacer for the first paragraph, so I had another problem. The picture I wanted to show is always the second picture, I sorted that one out too!

    Replace this line, and your second picture will turn up on your homepage:
    $first_img = $matches [1] [1]; //Setting to show 2nd picture, first picture: [1] [0]

    So, for all you people who also saw just the URL in your home-page, … this is it!
    LOL ;-P

  • http://www.lapietradaterra.com.ar Martín

    I figured out what the problem is. In some themes this hack just shows the URL of your 1st image and not the actual picture

  • http://postarticlesplus.net/ Alex Pablate

    Before now, I was not aware of hackers, but having visit your site I got overall knowledge about it. I agree with you that WordPress now has lots of advance developments that are helpful to protect our web site’s privacy!

    You are not providing only information but you are protecting our Internet community, that’s awesome!

    Keep it up pleas!

  • http://www.phpinterviewquestions.com Bart

    Great post. Keep up the wordpress hacking stuff.