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.

Comments (68) - Leave yours

  1. Denis said:

    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

  2. sriganesh said:

    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

  3. Jean-Baptiste Jung said:

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

  4. Johan de Jong said:

    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.

  5. Hirsute said:

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

  6. Rutje said:

    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

  7. Mark said:

    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

  8. Alex Shapovalov said:

    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 :)

  9. Kris Roxas said:

    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

  10. Flick said:

    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 :)

  11. Philippe Dionne said:

    Great post!

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

  12. Tony M said:

    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?

  13. Gonzo the Great said:

    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

  14. Alex Pablate said:

    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!

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!