Top 10 WordPress Hacks of All Time

Top 10 WordPress Hacks of All Time

Everywhere you look you will find articles that talk about the best new WordPress hacks of the year, or the latest hacks for the content management system, but with this article, I hope to show you what I think are the top WordPress hacks of all time, that still work with the popular and ever-growing content management system.

Top 10 WordPress Hacks of All Time

Top 10 WordPress Hacks

How to Display Adsense to Search Engine Visitors Only

Most of you that use Google Analytics probably know about the company’s smart pricing. What this “smart pricing” does is that for those publishers that aren’t bringing in enough clickthroughs for advertisers, Google will make it so that you make only about 10% of what you normally would per click.

With this hack, your blog will only show your Adsense ads to search engine visitors. The reasoning behind this is that most advertisement clicks come from search engine visitors, disabling Google’s smart pricing and earning the most money that you can.

To do this, we will create a function and paste it in our functions.php file in our theme folder:

function scratch99_fromasearchengine(){
  $ref = $_SERVER['HTTP_REFERER'];
  $SE = array('/search?', '', '', 'search.', '', '', '/search/', '.yahoo.');
  foreach ($SE as $source) {
    if (strpos($ref,$source)!==false) return true;
  return false;

In the $SE array, we specify all of the search engines we wish to display our ads to. We have some basic ones in there already, Google,,,, and Yahoo. Next, the code that will be used to display the ads on our site.

if (function_exists('scratch99_fromasearchengine')) {
  if (scratch99_fromasearchengine()) {

Just copy and paste that wherever you want ads, and insert the add code where it says INSERT YOUR CODE HERE.

Source: Avoid Smart Pricing Show Adsense Only to Search Engine Visitors

How to Display Dates as “Time Ago”

Many social networking sites such as Twitter, Reddit, Digg, and others use a format of displaying dates that we will call “Time Ago”. So if your post was on February 1st and today is February 10th, the date would be displayed as Posted 9 Days Ago. To do this, we will add this function to our themes functions.php.

function  timeAgo($timestamp, $granularity=2, $format='Y-m-d H:i:s'){
        $difference = time() - $timestamp;
        if($difference < 0) return '0 seconds ago';
        elseif($difference < 864000){
                $periods = array('week' => 604800,'day' => 86400,'hr' => 3600,'min' => 60,'sec' => 1);
                $output = '';
                foreach($periods as $key => $value){
                        if($difference >= $value){
                                $time = round($difference / $value);
                                $difference %= $value;
                                $output .= ($output ? ' ' : '').$time.' ';
                                $output .= (($time > 1 && $key == 'day') ? $key.'s' : $key);
                        if($granularity == 0) break;
                return ($output ? $output : '0 seconds').' ago';
        else return date($format, $timestamp);

Now to use this in our theme, you will want to place the following code anywhere within the loop to display the dates as “time ago” to a post.

$time = timeAgo($dateRef);

Source: Display Dates As Time Ago

Display an Incrementing Number on Each Post

There is a technique used on a very popular web design blog A List Apart, where they number every post that they make. Well, how would we accomplish this on our own website? First, let’s open up our functions.php file, and paste the following:

function updateNumbers() {
    global $wpdb;
    $querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' ";
    $pageposts = $wpdb->get_results($querystr, OBJECT);
        $counts = 0 ;
if ($pageposts):
    foreach ($pageposts as $post):
        add_post_meta($post->ID, 'incr_number', $counts, true);
        update_post_meta($post->ID, 'incr_number', $counts);

add_action ( 'publish_post', 'updateNumbers' );
add_action ( 'deleted_post', 'updateNumbers' );
add_action ( 'edit_post', 'updateNumbers' );

Now to show start using this, paste the following code inside the loop in any file you would like to show the number of your post (index.php, single.php, etc).

<?php echo get_post_meta($post->ID,'incr_number',true); ?>

Source: Top WordPress Hacks of Early 2010

Style Comments Based on User Roles

When your blog gets a fair amount of comments, it can be extremely useful to separate the comments by styling each comment made by a different user role separately. For example, if you are an administrator your comments could have a green background color, but if you were a subscriber the background would be gray.

The first step to achieving this will be and replacing your current comments loop in your comments.php file with the code below:

<ol id="commentlist">
<?php foreach ($comments as $comment) : ?>
        <?php // The extra stuff to get commenter's role
        $user_id = $comment->user_id;
        $role = ( isset( $roles[$user_id] ) ? $roles[$user_id] : '' );
        <li class="<?php echo $role; ?>">
        <p>By <?php comment_author_link() ?> - <?php comment_date() ?></p>
        <?php comment_text() ?>
<?php endforeach; ?>

Now you are prepared to style each role that leaves a comment on your blog. For the sake of keeping this tutorial short, we will only style not logged in users or subscribers, editors, and administrators. Put the code below in your style.css, and you can edit it however you feel fit.

#commentlist li { border:2px solid white; } /* not logged or subscriber */
#commentlist li.administrator { border:2px solid red } /* blog admin */
#commentlist li.editor { border:2px solid blue } /* editor */

Source: WordPress How to Style Comments of Every Roles

How to Add a Login Form Anywhere In Your Theme

By default, you can add a “Meta” widget to your WordPress blog in any sidebar that will link to where you can login or log out, as well as display a link to the dashboard. What if you just wanted to skip clicking that extra link, and just login straight from a form on your blog. Well, just add the code below to wherever you would like the form to be displayed, and that’s it.

<?php if (!(current_user_can('level_0'))){ ?>
<form action="<?php echo get_option('home'); ?>/wp-login.php" method="post">
<input type="text" name="log" id="log" value="<?php echo wp_specialchars(stripslashes($user_login), 1) ?>" size="20" />
<input type="password" name="pwd" id="pwd" size="20" />
<input type="submit" name="submit" value="Send" class="button" />
       <label for="rememberme"><input name="rememberme" id="rememberme" type="checkbox" checked="checked" value="forever" /> Remember me</label>
       <input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" />
<a href="<?php echo get_option('home'); ?>/wp-login.php?action=lostpassword">Recover password</a>
<?php } else { ?>
<a href="<?php echo wp_logout_url(urlencode($_SERVER['REQUEST_URI'])); ?>">logout</a><br />
<a href="http://XXX/wp-admin/">admin</a>
<?php } ?>

Source: Add a Login Form on Your WordPress theme

How to Show Related Posts Without a Plugin

There are a lot of plugins out there that can show related posts at the bottom of a post, but this code can be used to do just that without the need of a plugin, so you can put the related posts exactly where you wish, and customize how many are displayed as well. Just post this code wherever you would like the related posts to be shown usually in the single.php.

<?php  //for use in the loop, list 5 post titles related to first tag on current post
  $backup = $post;  // backup the current object
  $tags = wp_get_post_tags($post->ID);
  $tagIDs = array();
  if ($tags) {
    $tagcount = count($tags);
    for ($i = 0; $i < $tagcount; $i++) {
      $tagIDs[$i] = $tags[$i]->term_id;
      'tag__in' => $tagIDs,
      'post__not_in' => array($post->ID),
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <h3><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
      <?php endwhile;
    } else { ?>
      <h2>No related posts found!</h2>
    <?php }
  $post = $backup;  // copy it back
  wp_reset_query(); // to use the original query again

To change the number of related posts shown, find 'showposts'=>5, and change that 5 to however many posts you would like shown. You can also change what you would like shown if there are no related posts, by modifying No related posts found!, to whatever you’d like.

Source: Code Highlighting

How to Style Posts Individually

On a normal WordPress blog, each post that you make looks the same as the next, in terms of font, background color, and so on. Well, with this WordPress hack, you can style your WordPress posts individually if you would like, changing the background of the post, color, font, and much more. This can lead to a much more distinguished and original post, and can possibly appeal a lot more to readers.

Now, to accomplish this hack, you will first have to open up your single.php, and find the following piece of code:

<div class="post">

And replace that with the following:

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

Now, all you have to do is find whatever your post ID is, and you can style your posts using the #post-XXX id in your style.css.

#post-112 {
    background: #113355;

Source: Fahirsch Asked How to Style Posts Individually

How To Add Bio Info To Your WordPress Blog Posts

In the WordPress backend for user profiles there’s an option to add a bio to user profiles, and with this hack, you can make it so that these bios are shown at the bottom of each post. To start off, copy and paste the following code wherever you would like the bio to be shown in your single.php file.

<div id="author-bio">
	<h3>About <?php the_author(); ?></h3>
	<?php echo get_avatar( get_the_author_email(), '70' ); ?>
	<?php the_author_description(); ?>                        

Now to style this bio by using the author-bio id that we will create in our style.css that will make it look good.

#author-bio { border-top: 1px dotted #cccccc; padding: 15px 0; }
#author-bio h3 { font-size: 16px; margin: 0 0 5px 0; }
#author-bio img { float: left; padding: 2px; border: 1px solid #cccccc; margin: 5px 15px 0 0; }

Note that in the code we added in our style.css there is the code to get a gravatar, so make sure that, unless you want one of the defaults by WordPress shown, you register your email that you used for your blog with Gravatar and upload an avatar that can be shown in your author bio.

Creating Automatic Short URLs with

Sharing links to articles on your blog via social networking sites is a great way to boost the number of readers to your website. But with Twitter’s 140 character limit, there’s little room for long permalinks with the date and title of your blog post, as well as a personal note beside it to inform the reader what they’re clicking.

Why would you want to go all the way to and create a short URL every time you make a blog post, when it could be done automatically? Well with the code below, you no longer have to worry about manually creating short URL’s, just add the following code to your theme’s functions.php file:

function bitly($url) {
    $content = file_get_contents("
    $element = new SimpleXmlElement($content);
    $bitly = $element->data->url;
        echo $bitly;}
       echo '0';

Now if you would like to make this URL public and allow for users to copy and paste it for themselves, all you have to do is put the following anywhere in your theme’s single.php file within the loop:

<?php bitly(get_permalink($post->post_id)); ?>

Source: 5 Practical Ways to Integrate URL Shortening Services on Your Blog

Create an Ajax-based Auto-completing Search Field

If visitors on your blog are looking for something, why not help them out a little bit? This hack will use a technique popularized by Google, and will be what we call an auto-completing search field, that will show a dropdown list of tags based on what has already been typed into the search field.

To start this off you will need to download the latest version of jQuery , as well as the autocomplete plugin. Now, create a folder in your theme called “js” and place both of those files in it. Next, in the header.php of your theme, you will want to place the following code before the head tag.

<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.autocomplete.pack.js"></script>
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/js/jquery.autocomplete.css" media="screen" />

Now we will too add the following code before the head tag, and all you’ve got to do is replace $("#ID_OF_SEARCH_INPUT_BOX") with the actual id you use for your search box in your WordPress site.

<script type="text/javascript">
    var data = '<?php global $wpdb; $search_tags = $wpdb->get_results("SELECT name FROM $wpdb->terms"); foreach ($search_tags as $mytag){ echo $mytag->name. " "; } ?>'.split(" ");

Source: How to Create an Ajax Based Autocompleting Search Field for Your WordPress Theme


So those are what I think are the top 10 WordPress hacks in terms of usefulness, and compatibility with previous and current versions of the WordPress content management system. If you have any others that you would like to share, feel free to do so in the comments below and tell me why you like it!

Keenan Payne is a full time student and a freelance web designer in his spare time. Besides writing and web design, he loves to skateboard and snowboard, and has been doing both for 11 and 6 years respectively, although some would say it's getting progressively harder for him to step away from his work and wander outside.


  1. / Reply

    Great hack mushup Keenan :-)

    • Dir,
    • March 31, 2011
    / Reply

    great article and tricks. thanks for sharing. the trick with customizing each post is awesome. thanks

  2. / Reply

    I’m sorry, but I wouldn’t consider half of your examples “hacks”!
    Plus you’re promoting a bad coding style.

    How to Style Posts Individually
    Ever heard of the post_class() function? No “hack” necessary.

    How to Add a Login Form Anywhere In Your Theme
    Since 3.0 there’s a core function for that: wp_login_form(). Again: No “hack” necessary.

    How to Display Dates as “Time Ago”
    human_time_diff(). And again: No “hack” necessary.

    Show Your Top Contributors Without a Plugin
    Please, please remove that example asap! That is as horrible of WordPress coding as I have ever seen! Have a look at the comments section of the source blog post.

    a concerned WordPress Coder

    1. / Reply

      Hi Konstantin,

      We will revise the article and make the necessary changes.

      Thank you for the kind inputs and feedbacks.

    2. Thanks for taking the time to point these out.

    3. / Reply

      Hi Konstantin,

      We have replaced “Show Your Top Contributors Without a Plugin” with “Display an Incrementing Number on Each Post”.

      You may wish to take a look and offer your kind feedback.


  3. / Reply

    Alot of bad practise.
    – Why not use the WordPress DB Class when doing SQL queries?
    – Using short links instead of If you not doing spam content.

    1. / Reply

      Thanks for the comments, and I actually couldn’t find tutorials containing either of those for the collection of hacks that I put together, if you could point me the right direction for some I could give them a look over and put them up in the article.

    • david gyori,
    • March 31, 2011
    / Reply

    good collection, but if the visitor’s browser is ie, then HTTP_REFERER does’n exists, it’ll generate an error message.

    function scratch99_fromasearchengine(){
    if (isset($_SERVER[‘HTTP_REFERER’])) {
    $ref = $_SERVER[‘HTTP_REFERER’];
    $SE = array(‘/search?’, ‘’, ‘’, ‘search.’, ‘’, ‘’, ‘/search/’, ‘.yahoo.’);
    foreach ($SE as $source) {
    if (strpos($ref,$source)!==false) return true;
    return false;

    • Lukas,
    • April 1, 2011
    / Reply

    WTF is this???

    $content = file_get_contents(“”.$url.”&format=xml”);

    Just guess how long will it take to get your account banned, if any of your posts gets into facebook or something?

    Not talking about the performance. Each page load requires a connection to server. It can almost double you page load ( has to process your query too).
    Just try to read once :)

    Despite how much I enjoyed your previous posts, calling these ideas as hacks is almost offensive for any real hacker. Cracks at best :(

    1. / Reply

      Thanks for your comment, and I’ll be sure to check that out. And by calling these hacks, I was really meaning to encompass tricks and tips among hacks that can be used with WordPress. I didn’t literally mean it as hacking per se. Sorry if that was confusing.

  4. / Reply

    Create an Ajax-based Auto-completing Search Field it’s a good tip, but them load the database…

    • David,
    • April 1, 2011
    / Reply

    Unfortunately the Bio hack doesn’t work : (

  5. / Reply

    “Style Comments Based on User Roles” useful for me
    i implemented thank you “Onextrapixel”

  6. / Reply

    Thank you for WordPress Hacks

  7. / Reply

    Thanks for sharing this although there are any mistakes !
    And thanks to Lucas, Erik and Konstantin for pointing out, it’s a way of learning ;)

  8. / Reply

    i liked the author bio description hack. i would also like to know is there a way to show image of author from image galleryfrom wp installation not from gavatar.

    • DiliBau,
    • April 3, 2011
    / Reply

    $sql = “SELECT
    . “FROM
    . “WHERE “.$table_prefix.posts.”.”.post_parent.”=0
    . “Group by
    . “Order by count(*) DESC\n”
    . “Limit 0,10″;
    The above SQL code should give you some errors IMO. Shouldn’t ..”.$table_prefix.users.”…. be in fact …”.$table_prefix.”users….. ?

  9. / Reply

    Is that adsense hack “legal” ? I mean, it’s not against the Adsense TOS, is it?

  10. / Reply

    Nice Info. Very Usefull… Thanks a lot…

  11. / Reply

    I have a little Question. In the “Display an Incrementing Number on Each Post”, I have the effect :) but instead of incremental number, is more like the opposite. The newer posts get the higher numbers and get to 1.

    If you have a very recent post, his number need to be 1. ¿Isn´t obvious?, If not, looks like your posts are reversed, with the higher numbers first, and the lowers last, wich, at my test, everyone looks for the 1. to get the first post. The thing is, I cannot program, but I think is a simple change in the php, to get the posts, and assign the lower numbers to the most recents, and increment from here.

    Second, ¿Is truly explained how to integrate the “X days ago”? I cannot get it to work.

    Many thanks to all. This are very very useful. Like magic. xD

    1. / Reply

      About the “X days ago”, I´ve found this in the codex. No functions.php required. ¡Built-in!:

    • RSK,
    • April 27, 2011
    / Reply

    Loved this hack “How to Show Related Posts Without a Plugin”

  12. / Reply

    thanks for sharing such a nice post nice info very usefull

  13. / Reply

    Very nice article, Have used some of these hacks before and agree with the additional ones. Thanks for sharing them.

  14. / Reply

    Very good tricks. These tricks are very useful for a newbie like me. I was looking up to beautify my blog and these tricks just helped me out. Thanks for sharing :)

  15. / Reply

    Great post! thanks for sharing, Keenan. I added review of this website and linked to your post here:

  16. / Reply

    Thanks Keenan for sharing…
    I really have to try this out on my demo blog before i try them on my live blog due to the number of errors most people are already pointing out.

    Anyway Thanks

  17. / Reply

    is there is specific way to hack a wordpress site, Hacks not tricks.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Iconfinder Coupon Code and Review

Iconfinder offers over 1.5 million beautiful icons for creative professionals to use in websites, apps, and printed publications. Whatever your project, you’re sure to find an icon or icon…

WP Engine Coupon

Considered by many to be the best managed hosting for WordPress out there, WP Engine offers superior technology and customer support in order to keep your WordPress sites secure…

InMotion Hosting Coupon Code

InMotion Hosting has been a top rated CNET hosting company for over 14 years so you know you’ll be getting good service and won’t be risking your hosting company…

SiteGround Coupon: 60% OFF

SiteGround offers a number of hosting solutions and services for including shared hosting, cloud hosting, dedicated servers, reseller hosting, enterprise hosting, and WordPress and Joomla specific hosting.