10 Killer WordPress Hacks

2008 was a very good year for the WordPress community. The software was updated numerous times, leading to the recent release of version 2.7, and many new blogs dedicated to WordPress were created. Of course, tons of new hacks were discovered, which helped lots of bloggers enhance their blogs.

In this article, we’ll show you 10 new useful killer WordPress hacks to unleash the power of your favorite blogging engine. Each hack has an accompanying explanation, so you’ll not only unleash the power of WordPress but also understand how it works.

You may be interested in the following related articles as well:

[By the way, did you know we have a brand new free Smashing Email Newsletter? Subscribe now and get fresh short tips and tricks on Tuesdays!]

1. Display AdSense Ads to Search Engines Visitors Only

Sm7 in 10 Killer WordPress Hacks

The problem. It’s a known fact that regular visitors don’t click on ads. Those who do click on ads are, 90% of the time, visitors coming from search engines.

Another problem is Google’s “smart pricing.” Being smart priced means that your click-through rate (CTR) is low and the money you earn per click is divided by between 2 and 10. For example, if a click would normally earn you $1.00, with smart pricing it could earn you as little as $0.10. Painful, isn’t it? Happily, this solution displays your AdSense ads to search engine visitors only, which means more clicks and a higher CTR.

The solution.

  1. Open the functions.php file in your theme.
  2. Paste the following code in it:
    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;
    }
  3. Once done, paste the following code anywhere in your template where you want your AdSense ads to appear. They’ll be displayed only to visitors coming from search engine results:
    if (function_exists('scratch99_fromasearchengine')) {
      if (scratch99_fromasearchengine()) {
        INSERT YOUR CODE HERE
      }
    }

Code explanation. This hack starts with the creation of a function called scratch99_fromasearchengine(). This function contains a $SE array variable in which you can specify search engines. You can easily add new search engines by adding new elements to the array.

The scratch99_fromasearchengine() then returns true if the visitor comes from one of the search engines containing the $SE array variable.

Sources:

2. Avoid Duplicate Posts in Multiple Loops

Sm3 in 10 Killer WordPress Hacks

The problem. Due to the recent popularity of “magazine” themes, there’s a high demand from WordPress users who use more than one loop on their blog home page for a solution to avoiding duplicate posts on the second loop.

The solution. Here’s a simple solution to that problem, using the power of PHP arrays.

  1. Let’s start by creating a simple PHP array, and put all post IDs from the first loop in it.
    <h2>Loop n°1</h2>
    
    <?php
    $ids = array();
    while (have_posts()) : the_post();
    the_title();
    ?>
    <br />
    
    <?php $ids[]= $post->ID;
    endwhile; ?>
  2. Now, the second loop: we use the PHP function in_array() to check if a post ID is contained in the $ids array. If the ID isn’t contained in the array, we can display the post because it wasn’t displayed in the first loop.
    <h2>Loop n°2</h2>
    
    <?php
    query_posts("showposts=50");
    while (have_posts()) : the_post();
    if (!in_array($post->ID, $ids)) {
      the_title();?>
      <br />
    <?php }
    endwhile; ?>

Code explanation. When the first loop is being executed, all IDs of posts contained within it are put into an array variable. When the second loop executes, we check that the current post ID hasn’t already been displayed in the first loop by referring to the array.

Source:

3. Replacing “Next” and “Previous” Page Links with Pagination

Sm1 in 10 Killer WordPress Hacks

The problem. By default, WordPress has functions to display links to previous and next pages. This is better than nothing, but I don’t understand why the folks at WordPress don’t build a paginator by default. Sure, there are plug-ins to create pagination, but what about inserting it directly in your theme?

The solution. To achieve this hack, we’ll use the WP-PageNavi plug-in and insert it directly in our theme.

  1. The first thing to do, obviously, is download the plug-in.
  2. Unzip the plug-in archive on your hard drive, and upload the wp-pagenavi.php and wp-pagenavi.css files to your theme directory.
  3. Open the file that you want the pagination to be displayed in (e.g. index.php, categories.php, search.php, etc.), and find the following code:
  4. <div class="navigation">
    
    <div class="alignleft"><?php next_posts_link('Previous entries') ?></div>
    <div class="alignright"><?php previous_posts_link('Next entries') ?></div>
    </div>

    Replace this part with the code below:

    <?php
    include('wp-pagenavi.php');
    if(function_exists('wp_pagenavi')) { wp_pagenavi(); }
    ?>
  5. Now we have to hack the plug-in file. To do so, open the wp-pagenavi.php file and find the following line (line #61):
    function wp_pagenavi($before = '', $after = '') {
            global $wpdb, $wp_query;

    We have to call the pagenavi_init() function, so let’s do it this way:

    function wp_pagenavi($before = '', $after = '') {
    	global $wpdb, $wp_query;
            pagenavi_init(); //Calling the pagenavi_init() function
  6. We’re almost done. The last thing to do is to add the wp-pagenavi style sheet to your blog. To do so, open up header.php and add the following line:
    <link rel="stylesheet" href="<?php echo TEMPLATEPATH.'/pagenavi.css';?>" type="text/css" media="screen" />

Code explanation. This hack mostly consists of simply including the plug-in file directly in the theme file. We also had to add a call to the pagenavi_init() function to make sure the pagination would be properly displayed.

Source:

4. Automatically Get Images on Post Content

Sm4 in 10 Killer WordPress Hacks

The problem. Using custom fields to display images associated with your post is definitely a great idea, but many WordPress users would like a solution for retrieving images embedded in the post’s content itself.

The solution. As far as we know, there’s no plug-in to do that. Happily, the following loop will do the job: it searches for images in post content and displays them on the screen.

  1. Paste the following code anywhere in your theme.
    <?php if (have_posts()) : ?>
    
    <?php while (have_posts()) : the_post(); ?>
    
    <?php
    $szPostContent = $post->post_content;
    $szSearchPattern = '~<img [^\>]*\ />~';
    
    // Run preg_match_all to grab all the images and save the results in $aPics
    preg_match_all( $szSearchPattern, $szPostContent, $aPics );
    
    // Check to see if we have at least 1 image
    $iNumberOfPics = count($aPics[0]);
    
    if ( $iNumberOfPics > 0 ) {
         // Now here you would do whatever you need to do with the images
         // For this example the images are just displayed
         for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
              echo $aPics[0][$i];
         };
    };
    
    endwhile;
    endif;
    ?>

Code explanation. The above code basically consists of a simple WordPress loop. The only difference is that we use PHP and regular expressions to search for images within the post’s content instead of simply displaying posts. If images are found, they’re displayed.

Sources:

5. Create a “Send to Twitter” Button

Sm5 in 10 Killer WordPress Hacks

The problem. Are you on Twitter? If so, we’re sure you know how good this service is for sharing what you find interesting online with your friends. So, why not give your readers a chance to directly send your posts’ URLs to Twitter and bring you some more visitors?

The solution. This hack is very simple to achieve. The only thing you have to do is to create a link to Twitter with a status parameter. Because we’re using a WordPress blog, we’ll use the function the_permalink() to get the page URL:

<a href="http://twitter.com/home?status=Currently reading <?php the_permalink(); ?>" title="Click to send this page to Twitter!" target="_blank">Share on Twitter</a>

Pretty easy, isn’t it? But pretty useful too, in our opinion.

Source:

Related plug-in:

6. Using Normal Quotes Instead of Curly Quotes

Sm6 in 10 Killer WordPress Hacks

The problem. If you’re a developer who often publishes code snippets on your website, you have probably encountered the following problem: a user tells you that the code you posted doesn’t work. Why? Simply because, by default, WordPress turns normal quotes into so-called “smart quotes,” which breaks code snippets.

The solution. To get rid of theses curly quotes, proceed as follows:

  1. Open the functions.php file in your theme. If that file doesn’t exist, create it.
  2. Paste the following code:
    <?php remove_filter('the_content', 'wptexturize'); ?>
  3. Save the file, and say goodbye to broken code snippets!

Code explanation. The wptexturize() function automatically turns normal quotes into smart quotes. By using the remove_filter() function, we tell WordPress that we don’t want this function to be applied to a post’s content.

Source:

7. Deny Comment Posting to No Referrer Requests

The problem. Spam is a problem for every blogger. Sure, Akismet is there to help, but what about preventing spam just a bit more? The following code will look for the referrer (the URL from where the page was called) when the wp-comments-post.php file is accessed. If a referrer exists, and if it is your blog’s URL, the comment is allowed. Otherwise, the page will stop loading and the comment will not be posted.

The solution. To apply this hack, simply paste the following code into your theme’s function.php file. If your theme doesn’t have this file, just create it.

function check_referrer() {
    if (!isset($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == “”) {
        wp_die( __('Please enable referrers in your browser, or, if you\'re a spammer, bugger off!') );
    }
}

add_action('check_comment_flood', 'check_referrer');

Source:

8. Using CSS Sliding Doors in WordPress Navigaton

Sm2 in 10 Killer WordPress Hacks

The problem. The built-in wp_list_pages() and wp_list_categories() functions allow lots of things, but they do not allow you to embed a <span> element so that you can use the well-known CSS sliding-doors technique. Happily, with some help from PHP and regular expressions, we can use this awesome technique on a WordPress blog.

Due to the number of tutorials on CSS sliding doors, we’re not going to explain how it works here; consider reading this excellent article if you need to know more about the technique. To view a live demo of this example, click here and refer to the main menu.

  1. Create the images you need, and then edit the style.css file in your WordPress theme. Here is an example:
    #nav a, #nav a:visited {
    display:block;
    }
    #nav a:hover, #nav a:active {
    background:url(images/tab-right.jpg) no-repeat 100% 1px;
    float:left;
    }
    #nav a span {
    float:left;
    display:block;
    }
    #nav a:hover span {
    float:left;
    display:block;
    background: url(images/tab-left.jpg) no-repeat 0 1px;
    }
  2. Now it is time to edit the header.php file. Simply copy and paste one of the following codes, according to your needs:To list your pages:
    <ul id="nav">
    <li><a href="<?php echo get_option('home'); ?>/"><span>Home</span></a></li>
    
    <?php echo preg_replace('@\<li([^>]*)>\<a([^>]*)>(.*?)\<\/a>@i', '<li$1><a$2><span>$3</span></a>', wp_list_pages('echo=0&orderby=name&exlude=181&title_li=&depth=1')); ?>
    
    </ul>

    To list your categories:

    <ul id="nav">
    <li><a href="<?php echo get_option('home'); ?>/"><span>Home</span></a></li>
    <?php echo preg_replace('@\<li([^>]*)>\<a([^>]*)>(.*?)\<\/a>@i', '<li$1><a$2><span>$3</span></a>', wp_list_categories('echo=0&orderby=name&exlude=181&title_li=&depth=1')); ?>
    
    </ul>

Code explanation. In this example, we make use of the echo=0 parameter in the wp_list_pages() and wp_list_categories() functions, which allows you to get the result of the function without directly printing it on the screen. Then, the result of the function is used by the PHP preg_replace() function and finally displayed with <span> tags added between the <li> and <a> tags.

Source:

9. Display a Random Header Image on Your WordPress Blog

Sm9 in 10 Killer WordPress Hacks

The problem. This is not really a problem, but many WordPress users would love to be able to display a random header image to their readers.

The solution.

  1. Once you have selected some images to be your header images, name them 1.jpg, 2.jpg, 3.jpg and so on. You can use as many images as you want.
  2. Upload the images to your wp-content/themes/yourtheme/images directory.
  3. Open header.php and paste the following code in it:
    $num = rand(1,10); //Get a random number between 1 and 10, assuming 10 is the total number of header images you have
    
    <div id="header" style="background:transparent url(images/.jpg) no-repeat top left;">
  4. You’re done! Each page or post of your blog will now display a random header image.

Code explanation. Nothing hard here. We simply initialized a $num variable using the PHP rand() function to get a random number between 1 and 10. Then, we concatenate the result of the $num variable to the path of the theme we are using.

Source:

10. List Your Scheduled Posts

Sm10 in 10 Killer WordPress Hacks

The problem. Like many bloggers, you probably want your readers to visit your blog more often or subscribe to your RSS feed. A good way to make them curious about your future posts is by listing the titles of your scheduled posts.

The solution. Open any of your theme files and paste the following code:

<?php
$my_query = new WP_Query('post_status=future&order=DESC&showposts=5');
if ($my_query->have_posts()) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>

        <li><?php the_title(); ?></li>
    <?php endwhile;
}
?>

Code explanation. In this code, we have created a custom WordPress query using the WP_Query class to send a database query and fetch the five most recent scheduled posts. Once done, we use a simple WordPress loop to display the posts’ titles.

Sources:

  • How to: List scheduled posts
  • Den Leser in die Zukunft blicken lassen
    About these ads
    • jake
    • May 6th, 2011

    Thanks For this Post, this helped me solved my problem. Thanks!!

  1. I am really happy to glance at this website posts which contains plenty of valuable facts, thanks for
    providing these kinds of data.

  2. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your
    point. You obviously know what youre talking about, why waste your
    intelligence on just posting videos to your site when
    you could be giving us something informative to read?

    Austin

    • Art
    • December 12th, 2012

    What a information of un-ambiguity and preserveness of precious
    know-how concerning unexpected feelings.

  3. Great beat . I would like to apprentice even as you amend your web site, how could i subscribe for a blog site? The account helped me a appropriate deal. I had been tiny bit familiar of this your broadcast offered bright clear idea

  4. I was just seeking this information for a while.

    After 6 hours of

    continuous Googleing, at last I got it in your web site.
    I wonder what’s the lack of

    Google strategy that do not rank this type of informative sites in top of the list.

    Generally the top web sites are full of garbage.

  5. My partner and I stumbled over here coming from a different web page and
    thought I might as well check things out. I like what I see so
    now i’m following you. Look forward to going over your web page again.

  6. Wonderful website you have here but I was curious if you knew of any forums that cover the same topics discussed here?
    I’d really like to be a part of community where I can get suggestions from other experienced individuals that share the same interest. If you have any suggestions, please let me know. Many thanks!

  7. Terrific work! That is the type of information that are supposed to be shared across the internet.

    Shame on the search engines for no longer positioning this publish upper!
    Come on over and discuss with my website .
    Thank you =)

  8. Heya i’m for the first time here. I found this board and I find It really useful & it helped

    me out much. I hope to give something back and help others like you aided me.

  9. Do you have a spam problem on this blog; I also am a blogger, and I was
    wondering your situation; many of us have developed some nice procedures and we

    are looking to exchange methods with other folks, be sure

    to shoot me an e-mail if interested.

  10. Can I simply say what a comfort to discover a person that actually understands what they’re talking about online. You actually understand how to bring an issue to light and make it important. More people really need to check this out and understand this side of the story. It’s surprising you are
    not more popular given that you definitely have the gift.

  11. I know this if off topic but I’m looking into starting
    my own weblog and was curious what all is

    needed to get set up? I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very

    internet smart so I’m not 100% sure. Any suggestions or advice

    would be greatly appreciated. Many thanks

  12. I’m not that much of a internet reader to be honest
    but your sites really nice, keep it up! I’ll go ahead and bookmark your
    website to come back down the road. All the best

  1. January 8th, 2011
    Trackback from : 2010 in review « MalarVizhi
  2. September 8th, 2013
    Trackback from : Pet Clothes for Small Dogs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 204 other followers

%d bloggers like this: