10 More Useful WordPress Hacks [Code]
13/07/2011 | 8 Comments
WordPress is the No.1 open source Content Management System (CMS) of the world, often used as a blog publishing application, powered by PHP and MySQL. WordPress comes with standard functions and we can use plugins or code snippets to give our blog a different look or function(s).
![]()
Personally I prefer code snippets and hacks more than using a plugin to get a feature up and running, this because a code snippet is pure, while a plugin comes from a 3rd party and could be filled with non-valide codes or bloated codes? Use these hacks and throw away those unnecessary plugins
Today I want to share more useful WordPress hacks and code snippets which I’ve found on the many WordPress related blogs. But before I begin, as always, a short word of warning ..
Note: These hacks worked at the time they were published, but as new versions of WordPress are released, some may no longer work. Please backup your theme before attempting any hacks so you can restore things if something goes wrong.
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); </ol>
The function takes 3 parameters:
- timestamp: Your date
- granularity: How far you go in the precision of your date. Default is 2 (1 day, 15 hours ago)
- format: Desired format for the date. Default is Y-m-d H:i:s.
Using the timeAgo() function within WordPress
Using timeAgo() in WordPress is not hard at all. Use the following code within WordPress loop to display the “time ago” date of a post:
echo timeAgo(get_the_time('U'));
Source: phpsnippets
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: wprecipes
Empty Trash Automatically
If you want the posts & pages trash to empty automatically, just add this to the wp-config.php file. The number displayed in the function is the number of days between the emptying.
define('EMPTY_TRASH_DAYS', 5 );
Source: Lava 360
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.
No Source

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: woorkup.com
Display Your Facebook Fans
You don’t want your Facebook fans to feel left out. Use this snippet to show them off too – replace YOUR-PAGE-ID with your page ID.
<?php
$page_id = "YOUR PAGE-ID";
$xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query
&amp;amp;amp;amp;amp;amp;amp;amp;amp;query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
$fans = $xml->page->fan_count;
echo $fans;
?>
Source: Lava 360
Display Feedburner Counter
Proud of all your subscribers on Feedburner? Show them off to the world. Remember to change the feedburner address to your own.
<?php
$url = file_get_contents('https://feedburner.google.com/api/awareness/1.0/Get
FeedData?uri=YOUR FEED ADDRESS');
$begin = 'circulation="'; $end = '"';
$page = $url;
$parts = explode($begin,$page);
$page = $parts[1];
$parts = explode($end,$page);
$fbcount = $parts[0];
if($fbcount == '') { $fbcount = '0'; }
echo '<strong> '.$fbcount.' </strong> Subscribers';
?>
Source: webm.ag
Display Twitter Followers
This code uses the Twitter API and grabs its count from a XML feed, replace “USERNAME” with your Twitter username
<?php
$twit = file_get_contents('http://twitter.com/users/show/USERNAME.xml');
$begin = ''; $end = '';
$page = $twit;
$parts = explode($begin,$page);
$page = $parts[1];
$parts = explode($end,$page);
$tcount = $parts[0];
if($tcount == '') { $tcount = '0'; }
echo '<strong> '.$tcount.' </strong> Followers';
?>
Source: webm.ag
Create Custom Shortcodes
Shortcodes are a handy way of using code functions within your theme. The advantage of shortcodes is that they can be easily used with the WordPress post editor.
Add this code to your functions.php:
function helloworld() {
return 'Hello World!';
}
add_shortcode('hello', 'helloworld');
You can then use [hello] wherever you want to display the content of the shortcode.
Source:wp-snippets
Custom Title Length
This snippet will allow you to customise the length (by the number of characters) of your post title.
Paste this code into the functions.php:
function ODD_title($char)
{
$title = get_the_title($post->ID);
$title = substr($title,0,$char);
echo $title;
}
To use this function all you have to do is paste the below code into your theme files, remembering to change the ’20′ to what ever character amount you require:
<?php ODD_title(20); ?>
Source:orangedevdesign
Conclusion
There are loads of ways to customize your WordPress-theme, if you want a fast loading blogging site it’s time to ditch a lot of nonsense plugins and add some of these hacks instead. You just need to be a bit handy with programming/coding in PhP, HTML and CSS, .. or know somebody who can do it for you.
I hope you’ve enjoyed this article. If you’ve liked this article, please retweet, and share it with your friends on Facebook .. cheers!


Nice Hacks
Hi WDC Mumbai,
Thanks, I hope you enjoyed it! BTW: There are more hacks and code snippet Articles on the gonzoblog.nl (see related topics)
Cheers & Ciao ..
Thanks a lot for this collection of WP hacks
I will optimize few things to my new website about economy.
Hi Deals,
Glad you like them, now nuke some of your plugins and put these hacks in place! Your site will not only load faster, and you’ll have less cluttered and bloated Third-party codes in your theme ;-P
Good luck with it, Cheers & Ciao ..
Really liked the excerpt, I hope you publish more.
Hi rcrdlbl,
I’m always posting the latest Hacks and/or Code Snippets here on the gonzoblog.nl, so please stay tuned ;-P
Thanks for your comment, Cheers & Ciao ..