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?', 'images.google.', 'web.info.com', 'search.', 'del.icio.us/search', 'soso.com', '/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, Web.Info.com, Del.icio.us, Soso.com, and Yahoo. Next, the code that will be used to display the ads on our site.

if (function_exists('scratch99_fromasearchengine')) {
  if (scratch99_fromasearchengine()) {
    INSERT YOUR CODE HERE
  }
}

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);
                                $granularity--;
                        }
                        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):
        setup_postdata($post);
        $counts++;
        add_post_meta($post->ID, 'incr_number', $counts, true);
        update_post_meta($post->ID, 'incr_number', $counts);
    endforeach;
endif;
}  

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() ?>
        </li>
<?php endforeach; ?>
</ol>

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'))){ ?>
<h2>Login</h2>
<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" />
    <p>
       <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']; ?>" />
    </p>
</form>
<a href="<?php echo get_option('home'); ?>/wp-login.php?action=lostpassword">Recover password</a>
<?php } else { ?>
<h2>Logout</h2>
<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;
    }
    $args=array(
      'tag__in' => $tagIDs,
      'post__not_in' => array($post->ID),
      'showposts'=>5,
      'caller_get_posts'=>1
    );
    $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;
    color:#069;
    font-weight:bold;
}

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(); ?>                        
</div>

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 Bit.ly

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 bit.ly 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("http://api.bit.ly/v3/shorten?login=YOURLOGIN
    &apiKey=YOURAPIKEY
    &longUrl=".$url."&format=xml");
    $element = new SimpleXmlElement($content);
    $bitly = $element->data->url;
    if($bitly){
        echo $bitly;}
    else{
       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">
$(document).ready(function(){
    var data = '<?php global $wpdb; $search_tags = $wpdb->get_results("SELECT name FROM $wpdb->terms"); foreach ($search_tags as $mytag){ echo $mytag->name. " "; } ?>'.split(" ");
    $("#ID_OF_SEARCH_INPUT_BOX").autocomplete(data);
})
</script>

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

Conclusion

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!

Deals

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.