10 More WordPress Hacks for Easy Life

Published On November 24, 2009
35 Comments Leave a Comment

wordpress-hack

This post is a continuation of the “WordPress Hacks” posts that I wrote earlier.

If you liked those, you will love this one. Here goes :-

1. Fight Cross Browser Compatibility the WordPress Way

While designing a theme, there are numerous cross browser compatibility issues that raise their head, and most of the times we are left with no choice but revert to using conditional hacks. The following WordPress hacks can really save a lot of headache :-

Open your functions.php file in the theme folder and add the following code :-

[php]
<?php
add_filter(‘body_class’,’browser_body_class’);
function browser_body_class($classes) {
global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;

if($is_lynx) $classes[] = ‘lynx’;
elseif($is_gecko) $classes[] = ‘gecko’;
elseif($is_opera) $classes[] = ‘opera’;
elseif($is_NS4) $classes[] = ‘ns4’;
elseif($is_safari) $classes[] = ‘safari’;
elseif($is_chrome) $classes[] = ‘chrome’;
elseif($is_IE) $classes[] = ‘ie’;
else $classes[] = ‘unknown’;

if($is_iphone) $classes[] = ‘iphone’;
return $classes;
}
?>
[/php]

The above function adds the name of the browser (e.g, opera, safari etc.) to your tag like this :-

[php]<body class="home blog logged-in safari">[/php]

Now you being a theme designer can take help of this custom class and write your CSS accordingly if you are facing any compatibility issues with any browser. This can be called as “planning in advance“!

2. Schedule an Event using WordPress

Many of us already know that posts on a WordPress blog can be scheduled to be posted on future dates. But did you know that this alarm kind of function can be used for different other things too! Here is a practicle usage that lets your WordPress blog shoot out an e-mail to you every hour (A very handy function in case you want to know the uptime of your website – Just make a folder in your e-mail for such e-mails and read them later as log details). Add the following code into the functions.php file of your theme.

[php]
if (!wp_next_scheduled(‘my_task_hook’)) {
wp_schedule_event( time(), ‘hourly’, ‘my_task_hook’ );
}
add_action( ‘my_task_hook’, ‘my_task_function’ );

function my_task_function() {
wp_mail(‘you@yoursite.com’, ‘Automatic email’, ‘Hello, this is an automatically scheduled email from WordPress.’);
}
[/php]

You can define your e-mail and subject in the above code yourself.

3. Removing Unwanted Links from your Comments

Here is a neat function that lets you remove unwanted links from your comments. As before, place the following code in the functions.php file of the theme folder :-

[php]
function plc_comment_post( $incoming_comment ) {
$incoming_comment[‘comment_content’] = htmlspecialchars($incoming_comment[‘comment_content’]);
$incoming_comment[‘comment_content’] = str_replace( "’", ‘&apos;’, $incoming_comment[‘comment_content’] );
return( $incoming_comment );
}

function plc_comment_display( $comment_to_display ) {
$comment_to_display = str_replace( ‘&apos;’, "’", $comment_to_display );
return $comment_to_display;
}

add_filter(‘preprocess_comment’, ‘plc_comment_post’, ”, 1);
add_filter(‘comment_text’, ‘plc_comment_display’, ”, 1);
add_filter(‘comment_text_rss’, ‘plc_comment_display’, ”, 1);
add_filter(‘comment_excerpt’, ‘plc_comment_display’, ”, 1);
[/php]

Spammers Die! Yay!

4. Retrieving Posts within a Date Range

Sometimes you will need to pull posts between two specific dates from your blog. The code below allows you to do just that :-

[php]<?php
function filter_where($where = ”) {
$where .= " AND post_date >= ‘2009-03-17’ AND post_date <= ‘2009-05-03’";
return $where;
}
add_filter(‘posts_where’, ‘filter_where’);
query_posts($query_string);
while (have_posts()) :
the_post();
the_content();
endwhile;

?>
[/php]

You can copy and paste the above code anywhere within your template files. Just don’t forget to change the dates.

5. Using Multiple Loops without Duplication

If you need to break display your posts in different sections (like in Magazine themes), where you want to display a fixed number of posts first, and the remaining later, you can use this code to make multiple loops (with offsetting the fixed posts in the later loop).

The first loop that will pull and display 5 recent posts :-

[php]<?php
query_posts(‘showposts=5’);
$ids = array();
while (have_posts()) : the_post();
$ids[] = get_the_ID();
the_title();
the_content();
endwhile;
?>
[/php]

And, the second loop that will exclude the above posts and show the remaining ones :-

[php]<?php
query_posts(array(‘post__not_in’ => $ids));
while (have_posts()) : the_post();
the_title();
the_content();
endwhile;
?>
[/php]

This code basically pulls the post IDs that are not contained in the array $ids[].

6. Highlighting Searched Keywords in Search Results

If you need to highlight the searched text in your search results (which is not an option by default in WordPress), here is the solution that accomplishes this feat :-

  • Open up your search.php file from the theme folder.
  • Find the_title() function and replace it with :-
    [php]mytitle();[/php]
  • Add this code to your functions.php file
    [php]<?php
    function mytitle() {
    $mytitle = get_the_title();
    $keys= explode(" ",$s);
    $mytitle = preg_replace(‘/(‘.implode(‘|’, $keys) .’)/iu’,
    ‘<span class="searched">\0</span>’,
    $mytitle);
    echo $mytitle;
    }
    ?>
    [/php]
  • Open style.css file and add the following code:-
    [css].searched { background: yellow; font-weight:bold; }[/css]

We are done. Try searching some text on your blog now!

7. Display Related Posts without a Plugin

This is a good hack if you want to show “related posts” below the single post view on your blog without the use of a plugin. Just open the single.php file and paste the following code within the WordPress loop :-

[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);
echo "<div><h3>Related Posts</h3>";
$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() )
{
echo "<ul>";
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php endwhile;
echo "</ul>";
}
} else echo "<span>No related posts were found!</span>";
$post = $backup; // copy it back
wp_reset_query(); // to use the original query again
echo "</div>";
?>[/php]

The above code uses post “Tags” (that you have made in your posts) to relate the posts. So use them wisely!

8. Add your Posts to Facebook

The following hack will add a link within your posts that will allow users to share the post with their friends on Facebook. This can help in bringing extra traffic to your blog. Open the single.php file from your theme folder and paste this code within the loop where you want the link to show up :-

[php]<a href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php the_title(); ?>" target="blank">Share on Facebook</a>[/php]

Now the users will be able to share your posts!

9. Inserting Advertisements after Every First Post

Open up your index.php file and find the loop. Replace your loop with the following :-

[php]<?php if (have_posts()) : ?>
<?php $count = 0; ?>
<?php while (have_posts()) : the_post(); ?>
<?php $count++; ?>
<?php if ($count == 2) : ?>
//Paste your ad code here
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php else : ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
[/php]

You can paste your ad code where it says “//Paste your ad code here”. Your loop might not be exactly replaceable so you can take hints from the above code and modify your loop accordingly.

10. Automatic Content after Each Post

Many times, you want to add custom content/text after every post (e.g, subscribe to our blog link). Open up your functions.php file and add the following code to it :-

[php]
function insertFootNote($content) {
if(!is_feed() && !is_home()) {
$content.= "<div class=’subscribe’>";
$content.= "<h4>Enjoyed this article?</h4>";
$content.= "<p>Subscribe to our <a href=’http://feeds2.feedburner.com/WpRecipes’>RSS feed</a> and never miss a recipe!</p>";
$content.= "</div>";
}
return $content;
}
add_filter (‘the_content’, ‘insertFootNote’);
[/php]

I hope you enjoyed the above hacks and will make use of them. Please comment and let me know.

35 replies on “10 More WordPress Hacks for Easy Life”

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

Today, while I was at work, my cousin stole my iphone and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My apple ipad is now destroyed and she has 83 views. I know this is completely off topic but I had to share it with someone!

You’ve made some decent points there. I looked on the net for additional information about the issue and found most people will go along with your views on this website.

I was suggested this blog through my cousin. I am no longer positive whether or not this submit is written by way of him as nobody else know such precise approximately my problem. You are wonderful! Thank you!

Good post. I learn something new and challenging on blogs I stumbleupon everyday. It’s always interesting to read through articles from other authors and practice a little something from other web sites.

I have been browsing online more than 4 hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my view, if all web owners and bloggers made good content as you did, the internet will be much more useful than ever before.

I love the facebook code. I’ve added it to my blog. A suggestion would be to add a “title”, to provide a tool tip for the user clicking the link, just in case you don’t have enough space. The link would then be something like:
<a href="http://www.facebook.com/sharer.php?u=&t=” target=”blank” title =”Share this with your friends on Facebook!”>Share on Facebook

Thanks for the great ideas!
~ab

Awesome list of hacks,, some I allready do..lol Some I def will start to do… I like the Related Post hack,, right now I use Zemanta to add related posts sinc e I didnt want another pluigin.. but this hack will make life lil easier,,lol

10. Automatic Content after Each Post

Plugin correctly:

plugin.php
—-
function firstplug($text) {
$text .=”\n\n”;
$text .=’rss‘;
return $text;
}
add_filter(‘the_content’, ‘firstplug’, 5,1);

Once again another great list of hacks you’ve managed to come up with Jai! Thanks a lot for all of the ideas, I especially like the ads after the first post one, and the cross browser compatibility one. Thanks again! 🙂

There are some really great tips here, thanks. The email one particularly gives me some ideas–I’m wondering if one could modify the default emailing function for new comments to send a digest every hour rather than once for every comment. Could be a nice plug-in idea.

Leave a Reply

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