10 Exceptional WordPress Hacks

Advertisement

One of the reasons people love WordPress so much is its great flexibility. You can change the software’s appearance with themes. You can enhance its functionality with plug-ins. And, last but not least, you can totally unleash WordPress’ power with hacks. Some time ago, we wrote a post showing 10 Killer WordPress Hacks1.

Today, let’s do it again with 10 new and totally killer WordPress hacks to make your blog stand out from the crowd. As usual, we won’t just list the hacks alone. In each entry, you’ll find an explanation of the code as well as the kinds of problems that the hack solves.

You may be interested in the following related posts:

1. Create TinyURLs On The Fly

Screenshot

The problem. Because Twitter has become a social media revolution, many bloggers and Twitter users enjoy sharing blog posts they have found and liked on Twitter. However, manually creating a TinyURL before tweeting can get a little tedious. As you probably know, Twitter can bring a lot of traffic to your blog, so it is in your interest to consistently provide short URLs to your readers.

The solution. To use this recipe, follow the simple steps below:

  1. Open your functions.php file.
  2. Paste the following code in the file:
    function getTinyUrl($url) {
        $tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
        return $tinyurl;
    }
  3. Open your single.php file and paste the following in the loop:
    <?php
    $turl = getTinyUrl(get_permalink($post->ID));
    echo 'Tiny Url for this post: <a href="'.$turl.'">'.$turl.'</a>'
    ?>
  4. That’s all you need. Each of your posts now has its own TinyURL, ready for tweeting!

Code explanation. The popular URL shortening service TinyURL provides a quick API that creates TinyURLs on the fly. When you pass a URL to http://tinyurl.com/api-create.php, the API immediately prints the related TinyURL on the screen.

Using the PHP function file_get_contents(), we can get it and assign it to the $tinyurl variable. The last part of the code retrieves the post’s permalink and passes it as a parameter to the getTinyUrl() function previously created.

Source:

2. List Upcoming Posts

Screenshot

The problem. If you often schedule posts to be published, how about displaying them in a list? This will make your readers look forward to what you’re going to publish in a few days and can help you reach new RSS subscribers. Implementing this functionality on your WordPress blog isn’t hard at all.

The solution. Nothing hard here. Just copy this code and paste it anywhere in your theme files.

<div id="zukunft">
  <div id="zukunft_header"><p>Future events</p></div>

  <?php query_posts('showposts=10&post_status=future'); ?>
  <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <div >
      <p class><b><?php the_title(); ?></b><?php edit_post_link('e',' (',')'); ?><br />

      <span class="datetime"><?php the_time('j. F Y'); ?></span></p>
    </div>
  <?php endwhile; else: ?><p>No future events scheduled.</p><?php endif; ?>

</div>

Once you’ve saved the file, your upcoming posts will be displayed on your blog.

Code explanation. This code use the super-powerful query_posts() WordPress function, which allows you to take control of the WordPress loop.

The parameter used is post_status, which allows you to get posts according to their status (published, draft, pending or future). The showposts parameter is also used to define how many items you’d like to get. You can change the value of this parameter on line 4 to retrieve more or less than ten posts.

Source:

3. Create A “Send To Facebook” Button

Screenshot

The problem. In the first hack, we noted that Twitter can bring a lot traffic to your blog. Another website that can boost your traffic stats easily is Facebook. In this hack, let’s see how we can create a “Send to Facebook” button for your WordPress blog.

The solution.

  1. Open the single.php file in your theme.
  2. Paste the following code in the loop:
    <a href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php the_title(); ?>" target="blank">Share on Facebook</a>
  3. Alternatively, you could use the getTinyUrl() function to send a short URL to Facebook:
    <?php $turl = getTinyUrl(get_permalink($post->ID)); ?>
    <a href="http://www.facebook.com/sharer.php?u=<?php echo $turl;?>&t=<?php the_title(); ?>" target="blank">Share on Facebook</a>
  4. That’s all. Your readers will now be able to share your blog post on Facebook with their friends!

Code explanation. This useful hack is very easy to understand: the only thing we do here is retrieve the post’s permalink and title and send them as parameters to http://www.facebook.com/sharer.php.

In the alternative method, we used the getTinyUrl() function (created in the previous hack) to send a short URL instead of the post’s permalink.

Source:

4. Create A Maintenance Page For Your WordPress Blog

Screenshot

The problem. One thing I really like about Drupal is the option to temporarily redirect visitors to a maintenance page. Sadly, WordPress doesn’t have this feature. When you upgrade your blog, switch themes or make design changes, you may not want your visitors to see your blog as it is being tweaked, especially if it has design or code problems or, even worse, security gaps.

The solution. To solve this problem, we use the power of the .htaccess file. Just follow the steps below to get started.

  1. Create your maintenance page. A simple WordPress page is generally sufficient.
  2. Find your .htaccess file (located at the root of your WordPress installation) and create a back-up.
  3. Open your .htaccess file for editing.
  4. Paste the following code:
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !/maintenance.html$
    RewriteCond %{REMOTE_ADDR} !^123.123.123.123
    RewriteRule $ /maintenance.html [R=302,L]
  5. Replace 123.123.123.123 on line 3 with your IP address (Don’t know it?9). Make sure to use the same syntax.
  6. Now, all visitors except you will be redirected to your maintenance page.
  7. Once you’re done tweaking, upgrading, theme switching or whatever, re-open your .htaccess file and remove (or comment out) the redirection code.

Code explanation. The .htaccess file, which controls the Apache Web server, is very useful for these kinds of tasks.

In this example, we state that any visitor who has an IP different from 123.123.123.123 (which doesn’t request maintenance.html) should be redirected to maintenance.html.

By replacing 123.123.123.123 with your own IP address, you make sure you’re still allowed to browse your blog normally, while others are redirected to maintenance.html.

Source:

Screenshot

The problem. One well-known way of keeping visitors on your blog longer and helping them discover news posts is to display, usually at the end of the article, a list of related content.

Many plug-ins will do this job, but why not super-charge your theme by integrating this functionality by default?

The solution.

  1. Open the single.php file in your theme.
  2. Paste the following code in the loop:
    <?php
    //for use in the loop, list 5 post titles related to first tag on current post
    $tags = wp_get_post_tags($post->ID);
    if ($tags) {
      echo 'Related Posts';
      $first_tag = $tags[0]->term_id;
      $args=array(
        'tag__in' => array($first_tag),
        '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(); ?>
          <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
          <?php
        endwhile;
      }
    }
    ?>
  3. Save the file, and then have a look at your blog: related posts are automatically displayed!

Code explanation. This hack uses tags to retrieve related posts. The first thing it does is get the post’s tags. If a post has tags, the first one is extracted and used in a query that retrieves posts with the same tag.

By default, this code displays up to five related posts. To change this number, simply edit line 9 of the code.

Source:

6. Automatically Retrieve The First Image From Posts On Your Home Page

Screenshot

The problem. Many WordPress users use custom fields to display a thumbnail on their blog home page. Of course, this is a nice solution, but how about automatically retrieving the first image from a post and using it as a thumbnail?

The solution. This hack is quite easy to implement:

  1. Open the functions.php file in your theme.
  2. Paste this code in. Don’t forget to specify a default image on line 10 (in case a post of yours does not have an image).
    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;
    }
  3. Save the functions.php file.
  4. On your blog home page (index.php), call the function this way to get the URL of the first image from the post:
    <?php echo catch_that_image() ?>

Code explanation. The function uses the global variable $post to parse the post’s content with a regular expression. If an image is found, its URL is returned by the function. If not, the default image URL is returned.

Source:

7. Resize Images On The Fly

Screenshot

The problem. When you use thumbnails on your blog’s home page or even images in posts, having to manually resize them is boring and wastes a lot of time. So, why not use the power of PHP to do it?

The solution. To achieve this hack, just follow these simple steps:

  1. Get this script14 and save it on your computer (I’ll assume you’ve named it timthumb.php).
  2. Use an FTP program to connect to your server and create a new directory called scripts. Upload the timthumb.php file to it.
  3. Once done, you can display images like so:
    <img src="/scripts/timthumb.php?src=/images/whatever.jpg&h=150&w=150&zc=1" alt="Screenshot" />

    In other words, you just call the timthumb.php file and pass your image as a parameter. The same goes for your desired width and height.

Code explanation. The timthumb.php script use the PHP GD library, which allows you to manipulate images dynamically with PHP. GD is installed by default on all servers running PHP5. If you’re not running PHP5, you’ll have to check if GD is installed before using this script.

The timthumb.php file gets the parameters you’ve passed to it (image URL, width and height) and uses it to create a new image with your stated dimensions. Once that’s done, the image is returned to you.

Source:

Screenshot

The problem. Displaying your most popular posts is a good way to make visitors stay longer on your blog, as is displaying related posts. Many great plug-ins can list your most popular posts, but again, why use a plug-in when you can simply hack your WordPress theme to do it automatically?

The solution. Just paste the following code anywhere in your theme files (for example, in sidebar.php). To change the number of displayed posts, simply change the “5” on line 3 to your desired number.

<h2>Popular Posts</h2>
<ul>
<?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 5");
foreach ($result as $post) {
setup_postdata($post);
$postid = $post->ID;
$title = $post->post_title;
$commentcount = $post->comment_count;
if ($commentcount != 0) { ?>

<li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>">
<?php echo $title ?></a> {<?php echo $commentcount ?>}</li>
<?php } } ?>

</ul>

Code explanation. This code executes an SQL query to the WordPress database, using the $wpdb object, to get a list of the five posts with the most comments. The results are then wrapped in an unordered HTML list and displayed on screen.

Source:

9. Highlight Searched Text In Search Results

Screenshot

The problem. The WordPress search engine system is often criticized for not being powerful enough. One of its weakest points in my opinion is that searched text is not easily distinguishable from the rest of the text. Let’s solve that!

The solution.

  1. Open your search.php file and find the the_title() function.
  2. Replace it with the following:
    echo $title;
  3. Now, just before the modified line, add this code:
    <?php
      $title  = get_the_title();
      $keys= explode(" ",$s);
      $title  = preg_replace('/('.implode('|', $keys) .')/iu',
        '<strong class="search-excerpt"></strong>',
        $title);
    ?>
  4. Save the search.php file and open style.css. Add the following line to it:
    strong.search-excerpt { background: yellow; }

That’s all. Better, isn’t it?

Code explanation. Once again, regular expressions are a lifesaver. The regexp parses the $s content ($s is the variable containing the searched text) and automatically adds a <strong class=”search-excerpt”> element around any occurrences of $s.

Then, you simply modify your style.css file to give searched text a special style and make it more visible to your readers.

Sources:

10. Disable Widgetized Areas Without Editing Theme Files

Screenshot

The problem. Widgets are very useful, but sometimes you don’t need them on a particular page or post. Sure, you can create a page template for a particular page or even remove the widgetized zone from the code, but a much better and more elegant solution exists.

The solution. To do this, simply add the following code to your functions.php file:

<?php
add_filter( 'sidebars_widgets', 'disable_all_widgets' );

function disable_all_widgets( $sidebars_widgets ) {
  if ( is_home() )
    $sidebars_widgets = array( false );
  return $sidebars_widgets;
}
?>

Code explanation. This code first adds a filter to the sidebars_widgets WordPress function. Now every time WordPress tries to execute this function, it will execute the disable_all_widgets function we just created.

The disable_all_widgets function uses WordPress conditional tags (in this example, is_home(), but you can use any conditional tag) to disable all widgets if a visitor is on a particular page or post.

Source:

You may be interested in the following related posts:

(al)

Footnotes

  1. 1 http://www.smashingmagazine.com/2009/01/07/10-killer-wordpress-hacks/
  2. 2 http://www.smashingmagazine.com/2009/03/04/15-useful-twitter-plugins-and-hacks-for-wordpress/
  3. 3 http://www.smashingmagazine.com/2009/02/02/mastering-wordpress-shortcodes/
  4. 4 http://www.smashingmagazine.com/2008/12/18/8-useful-wordpress-sql-hacks/
  5. 5 http://www.smashingmagazine.com/2008/12/02/10-useful-rss-hacks-for-wordpress/
  6. 6 http://www.wprecipes.com/how-to-automatically-provide-tinyurls-for-your-wordpress-blog-posts
  7. 7 http://www.wprecipes.com/how-to-list-future-posts
  8. 8 http://www.wprecipes.com/how-to-add-a-share-on-facebook-link-to-your-wordpress-blog
  9. 9 http://www.ip-adress.com/
  10. 10 http://www.catswhocode.com/blog/10-awesome-htaccess-hacks-for-wordpress
  11. 11 http://www.wprecipes.com/how-to-show-related-posts-without-a-plugin
  12. 12 http://www.wprecipes.com/how-to-get-the-first-image-from-the-post-and-display-it
  13. 13 http://wordpress.org/support/topic/246893
  14. 14 http://timthumb.googlecode.com/svn/trunk/timthumb.php
  15. 15 http://www.darrenhoyt.com/2008/04/02/timthumb-php-script-released/
  16. 16 http://www.wprecipes.com/how-to-resize-images-on-the-fly
  17. 17 http://www.problogdesign.com/wordpress/create-your-own-popular-posts-page/
  18. 18 http://yoast.com/wordpress-search/
  19. 19 http://www.wprecipes.com/how-to-enlight-searched-text-in-search-results
  20. 20 http://justintadlock.com/archives/2009/03/06/disable-widget-areas-without-touching-theme-templates
  21. 21 http://www.smashingmagazine.com/2009/03/04/15-useful-twitter-plugins-and-hacks-for-wordpress/
  22. 22 http://www.smashingmagazine.com/2009/02/02/mastering-wordpress-shortcodes/
  23. 23 http://www.smashingmagazine.com/2009/01/26/10-steps-to-protect-the-admin-area-in-wordpress/
  24. 24 http://www.smashingmagazine.com/2008/12/18/8-useful-wordpress-sql-hacks/
  25. 25 http://www.smashingmagazine.com/2008/12/02/10-useful-rss-hacks-for-wordpress/

↑ Back to top Tweet itShare on Facebook

This guest post was written by Jean-Baptiste Jung, a 28-year-old blogger from Belgium, who blogs about Web Development on Cats Who Code, about WordPress at WpRecipes and about blogging on Cats Who Blog . You can stay in touch with Jean by following him on Twitter.

Advertisement
  1. 1

    Nice, looks like I’ll have to add related post, popular, and might even add “Highlight Searched Text In Search Results” into themes I design from now on.

    0
  2. 52

    You read my mind! I’m about to makeover my current blog template. Great article anyway..!

    0
  3. 103

    How am I suppose to do this for my content instead of my title???

    <?php the_content("Continue Reading - " . the_title('', '', false)). ""; ?>

    0
  4. 154

    Great article!!!
    I tried #6 before but its not working

    0
  5. 205

    Great and helpful post. Thanks.

    0
  6. 256

    Related Posts and Popular Posts without the plugins are great ideas!

    0
  7. 307

    Amazing Article, just one thing to point out, the .htaccess section (Point 4) the [R=302] flag should be changed to [R=307] – 302 redirects are VERY bad for SEO and if Google comes past at the time of that maintenance page being up, it will index that content, which is not good. Using a 307 redirect will prevent indexing of the maintenance page and tell Google to come back later.

    0
  8. 358

    All of that can be done with MODx, Concrete5 or EE without “hack” or php programming…

    Well, that’s the difference between real CMS’s and powerful but hacked blog platform.

    0
  9. 409

    And here is the code for the to.ly url shortening service:

    change the hxxp to http :

    function getTinyUrl($url) {
    $tinyurl = file_get_contents(“hxxp://to.ly/api.php?longurl=”.$url);
    return $tinyurl;
    }

    0
  10. 460

    je_braquerai_bien_votre_compte_de_pub

    April 16, 2009 7:10 am

    lol you call that “exceptional wordpress hacks”, i call that “some lines of code”

    0
  11. 511

    @Lindsay Lee
    Wordpress is a great tool for blogs, or even CMS. It can make your life much easier. As a web designer. graphic designer or w/e you do, I think using WordPress is much better option then creating your own blog/CMS. You can tweek WordPress backend to add functionalities you need. Good Luck!

    0
  12. 562

    why doesn’t Smashing Magazine add a easy functionality of replying to other people’s comments? This way commenter’s can have a good discussion going. And Subscribe to comments would be a good addition.

    0
  13. 613

    Your post states that there is no WP plugin that exists to put the site “on maintenance mode” when you are making changes on the site. This is not true. The Maintenance Mode plugin, which has been around puts up a splash page while maintenance is being done. You can get more details about it here http://wordpress.org/extend/plugins/maintenance-mode/

    0
  14. 664

    I think Smashing Magazine needs a better “comments” plugin… The number of comments displayed at the top of the article does not match the number of comments that are actually displayed. Is it counting pending ones? That would be quite odd… Does WP always do that?

    @Sharon: Good find on the Maintenance Mode plugin.

    0
  15. 715

    garrick Van Buren

    April 16, 2009 4:47 pm

    Andy, I wrote up a quick WordPress hack to make short URLs that are native to your blog: http://garrickvanburen.com/archive/wordpress-url-shortening-hack
    It’s 2 lines of code (one in the htaccess file and one in your templates file).

    0
  16. 766

    Great article! Thank for sharing!

    0
  17. 817

    this will be great help for wordpress users and developers too for learn more advanced techniques.

    Casper

    0
  18. 868

    these are some really use full ones and I have used for 1 of my clients and it saved me my time

    0
  19. 919

    Good… I’ve used in my blog Get Your Most Popular Posts Without A Plug-In with some differences

    0
  20. 970

    Oops, the ‘Display Related Posts Without A Plug-In’ part has a bug which will change the comment form’s performance if it is put right before the ‘comment_template()’.

    0
  21. 1021

    Love this post. Got some great tips here. I especially like the tip on how to disable widgets on certain pages.

    0
  22. 1072

    #5 – you have error in the code, it won’t work like that, there is a bit more code to be added, just like in the link you provided.

    0
  23. 1123

    Wow,Thanks
    Link

    0
  24. 1174

    Great hacks ..

    Thanks for sharing

    0
  25. 1225

    Nobody noticed that “5. – related posts” will actually throw error? Did you guys test it at all before publishing on the site? Besides, even if you add this extra } it won’t print anything at all cos the code is not complete. Anyway, I like the article, well done.

    0
  26. 1276

    excelente aporte, sobre todo ese manejo de los post mas leidos y los articulos relacionados en wordpress.

    0
  27. 1327

    I think tips like these are really useful for us designers who code, whereas for developers maybe less so. It depends on your own needs. Personally, I love this kind of short and sweet guide which tell you exactly how to accomplish a specific task in an efficient manner. So thanks Jean-Baptiste. Nice work.

    I’m with you, @cdoggyd, it’s getting a bit silly now. And how many other blogs have followed suit?!?

    And by the way, @Sharon and others, there is more than one WP plug-in to put your blog in suspended animation.

    0
  28. 1378

    Top notch article!! Thanks for putting this together.

    0
  29. 1429

    Has anyone noticed that on point 6 – “Automatically Retrieve The First Image From Posts On Your Home Page” the code has an error on line number 9 where it says

    if(emptyempty($first_img)){ //Defines a default image

    should be

    if(empty($first_img)){ //Defines a default image

    0
  30. 1480

    Design was here

    April 23, 2009 2:19 am

    Really Great and Useful WP Hacks!

    I think WP should make a maintenance page like Drupal.

    Thanks!

    0
  31. 1531

    For : 6. Automatically Retrieve The First Image From Posts On Your Home Page

    Just keep in mind that if you are showing a lot of articles on a page (on your home page for example), this searching through your articles will cause a delay on page load and can cause complaints from your provider if you’re on shared hosting.

    What i did was create an extra field to which this function can save the URL. if the extra field exists on the next load, it wont have to scan through all the text… saving resources and time :)

    More info : http://inztinkt.com/blog/2009/05/03/getting-first-image-from-wordpress-post-without-killing-your-server/

    0
  32. 1582

    Carlos Varela

    May 6, 2009 4:02 pm

    the tip four, is a good solution but is a better way use WP-Lock when you have a dynamic IP

    :)

    0
  33. 1633

    Joshua Unseth

    May 7, 2009 7:38 am

    For those of you wanting to integrate TimThumb with this code, you can find working code at Spidermarket’s Retrieve a Post’s First Image and Resize it with TimThumb. It’s a modification of the code found on WP Recipes’How to: Get the first image from the post and display it.

    0
  34. 1684

    thanks friend… need to add some of this to my site

    0
  35. 1735

    Love the first hack for tinyurl, but I’d rather use it with a Snipurl/Snipr. Great article!

    0
  36. 1786

    nice! i was looking for some of those for awhile. Thanks!

    0
  37. 1837

    Thanks for the great post. I’m trying to get rid of plug-ins this will help a lot.

    0
  38. 1888

    Nice tips but not for complete beginners – too many security holes, great post other wi$e thanx

    1
  39. 1939

    Top notch article!! Thanks for putting this together.

    consacepo

    0
  40. 1990

    Top notc h article!! Tha nks for putting this togeth er.

    consacepo

    0
  41. 2041

    How do I change so my search result once again starts displaying “read more” instead of […], I have that function in my functions-file, and before I applied that hack it worked fine, but now once again shows […]?

    0
  42. 2092

    Well. I did try related posts hack for my website. But the problem is it shows comment that is not related to post, infact it shows the comments related to last related post. i.e if my article is on java twitter mobile apps. and i have two related posts x and y then it will show the comments of y post instead of “java twitter mobile apps”. I guess it is a problem with looping. I’m placing it in wrong place or something else?

    0
  43. 2143

    Thanks, this has really been helpful in the development of my new blog.

    0
  44. 2194

    The related articles snippet is bugged. When I apply it to my post it takes the comments from another article and places it in an incorrect article.

    0
  45. 2245

    Great post.. I’ve used a number of these examples and they work great!

    One question, if you wanted to add a ‘Hot’ or ‘Popular’ image to your top 10 most popular posts.. what would be the best snippet to do that with ???

    So, when a visitors is viewing one of the top 10 most popular posts, a div is shown (I’ll then use CSS to style the div, etc.)

    0

↑ Back to top