10 useful new WordPress hacks

by Jean. 38 Comments -

WordPress is the platform of choice for most bloggers, and WordPress hacks is one of the most popular topics on CatsWhoCode. This is why I’ve decided to compile 10 new and extremely useful hack for WordPress. Enjoy!

Remove comments autolinks

If someone leaves a comment containing a url, the url will be automatically transformed to a link by WordPress. This can be useful, but personally I don’t like to see many links in comments, especially when they’re a bit spammy.
This is why I decided, on the latest CWC theme, to remove comments autolink. Doing so is pretty easy, just paste the following into your functions.php file. Once you saved the file, you’ll notice that autolinks have disappeared.

remove_filter('comment_text', 'make_clickable', 9);

» Source: http://www.wprecipes.com/wordpress-hack-remove-autolinks-in-comments

Automatically notify your users of new posts

If you run a private site using WordPress, then it could be useful to notify your users when a new post is published. The following snippet will get all user emails from your database and will send an email to them automatically when a post is published.
Of course, you shouldn’t use that code on your blog as it does not currently have any unsubscribe option.

function email_members($post_ID)  {
    global $wpdb;
    $usersarray = $wpdb->get_results("SELECT user_email FROM $wpdb->users;");
    $users = implode(",", $usersarray);
    mail($users, "New WordPress recipe online!", 'A new recipe have been published on http://www.catswhocode.com');
    return $post_ID;
}

add_action('publish_post', 'email_members');

Twitter style “time ago” dates

Displaying dates using the “5 days ago” format is becoming very popular on blogs, thanks to Twitter popularity.
I have seen lots of complicated tutorials to use this format on your WordPress blog, however many people don’t know that WordPress has a built-in function to do the same thing: human_time_diff().

Paste the snippet below anywhere within the loop, and it will display your dates using the “time ago” format.

Posted <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?>

» Source: http://www.phpsnippets.info/display-dates-as-time-ago

Display post thumbnail in your RSS feed

Introduced in WordPress 2.9, the the_post_thumbnail() function is very useful to easily add and display a thumbnail attached to a post. Unfortunately, there’s no built-in way to display this thumbnail on your RSS feed.

Happily, the function below will solve this problem. Simply paste it in your functions.php, save it, and the post thumbnail will be automatically displayed on your RSS feed.

function diw_post_thumbnail_feeds($content) {
	global $post;
	if(has_post_thumbnail($post->ID)) {
		$content = '<div>' . get_the_post_thumbnail($post->ID) . '</div>' . $content;
	}
	return $content;
}
add_filter('the_excerpt_rss', 'diw_post_thumbnail_feeds');
add_filter('the_content_feed', 'diw_post_thumbnail_feeds');

» Source: http://digwp.com/2010/06/show-post-thumbnails-in-feeds/

Block external requests

By default, WordPress does some external requests in order to get the available updates and the WordPress news shown in your dashboard. Personally, I don’t mind them, but I’ve recently had clients who didn’t wanted any external requests. So, I’ve blocked them using this interesting hack.
Simply add the following line to your wp-config.php file:

define('WP_HTTP_BLOCK_EXTERNAL', true);

If you need to allow some external requests, it it easy to create a whitelist, as shown below:

define('WP_ACCESSIBLE_HOSTS', 'rpc.pingomatic.com');

This line of code have to be pasted in wp-config.php as well.
» Source: http://digwp.com/2010/08/pimp-your-wp-config-php/

Easy debug mode

When things go wrong, you can always use the super useful WordPress debug tool, WP_DEBUG. By default, you have to paste a line of code in your wp-config.php to make the debug mode available.
By if you need to easily access the debug mode even when your site is live, you should edit your wp-config.php file and replace

define('WP_DEBUG', true);

by:

if ( isset($_GET['debug']) && $_GET['debug'] == 'debug')
  define('WP_DEBUG', true);

Once done, simply add a GET parameter to the url of the page you’d like to debug, as shown below:

http://www.catswhocode.com/blog/about?debug=debug

Of course, for obvious security reasons you should replace the name debug by a random word of your choice so no one will ever see your site in debug mode.
» Source: http://yoast.com/wordpress-debug/

Use WordPress shortcode in theme files

WordPress shortcodes are a super easy way to add content such as rss feeds, google maps, galleries and more into your posts or pages. But what about being able to output shortcodes in your theme files?
A built-in function exists, but most people never heard of it. The function is called do_shortcode(). It takes one parameter, the shortcode you’d like to display. I’ve heard you can ad more than one shortcode as a parameter, but I haven’t tried it yet.

do_shortcode('[gallery]
');

» Source: http://codex.wordpress.org/Function_Reference/do_shortcode

Allow upload of more file types

If you ever tried to upload some not so common filetypes, such as Textmate’s .tmCommand to your WordPress blog, you may have experienced an error, because WordPress simply doesn’t want you to upload some other file type.
Fortunately, you can add new file types to WordPress whitelist. Doing so is quite easy, just paste the following piece of code in your functions.php, and you’re done.
Note that file types have to be separated by a pipe.

function addUploadMimes($mimes) {
    $mimes = array_merge($mimes, array(
        'tmbundle|tmCommand|tmDragCommand|tmSnippet|tmLanguage|tmPreferences' => 'application/octet-stream'
    ));

    return $mimes;
}

add_filter('upload_mimes', 'addUploadMimes');

» Source: http://www.wprecipes.com/wordpress-tip-allow-upload-of-more-file-types

Google Docs PDF viewer shortcode

Google Docs is definitely the easiest way to read documents in .pdf, .doc or .xls online. So, if you want to share a PDF file with your readers, what about creating a shortcode that will open the PDF in Google Docs instead of forcing download?

Simply paste the code in your functions.php.

function pdflink($attr, $content) {
	return '<a class="pdf" href="http://docs.google.com/viewer?url=' . $attr['href'] . '">'.$content.'</a>';
}
add_shortcode('pdf', 'pdflink');

Once you saved the file, you’ll be able to use the shortcode on your posts and page. Here is the syntax:

[pdf href="http://yoursite.com/linktoyour/file.pdf"]View PDF[/pdf]

» Source: http://www.wprecipes.com/wordpress-tip-create-a-pdf-viewer-shortcode

Detect the visitor browser within WordPress

Well, this hack is not so new, but it still remains one of my favorites. What this code does is pretty simple, it detects the name of the visitor browser and adds it to the body_class() function.
That way, you can correct browser-specific problems extremely easily. The function has to be pasted in your functions.php file.

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;
}

The function output will look like:

<body class="home blog logged-in safari">

» Source: http://www.nathanrice.net/blog/browser-detection-and-the-body_class-function/

  • Simon

    I would like to know how time ago could be changed from 10 days ago to the date for example. No one bothers to see 150 days ago imo.

  • http://danielgrieve.co.uk Daniel

    Posted &lt;?php

    $daysAgo = human_time_diff(get_the_time('U'), current_time('timestamp'));

    echo ($daysAgo

    I didn’t fill in the DATEVARIABLE bit because I can’t remember how to show the post date in WordPress, woops :( But that should do what you’re looking for Simon.

  • http://www.joshrucker.com Josh Rucker

    I was unaware of the “time ago” function being built in…

  • http://www.masalife.com huarong

    great post.

    define(‘WP_ACCESSIBLE_HOSTS’, ‘rpc.pingomatic.com’);

    what to do if I have two or three WP_ACCESSIBLE_HOSTS?

    • http://www.wprecipes.com Jean-Baptiste Jung

      Thanks :)

      You can do this:
      define (‘WP_ACCESSIBLE_HOSTS’, ‘api.wordpress.org, akismet.com’);

  • http://blog.creative-webdesign.info Andi

    The document viewer shortcode is simple and nice.

  • http://www.dollarshower.com Ajith Edassery

    Awesome tips. I particularly liked the ‘time ago’ hack and I never knew about do_shortcode :)

    The browser detection, though, may not be of much use at the moment??

  • http://blog.ashfame.com Ashfame

    [php][/php] function returns the value and doesn’t echo it. So, it should be [php][/php]

    Code got stripped out earlier.

  • http://blog.ashfame.com Ashfame

    Disgusted!

    Just use echo before do_shortcode()

    • http://www.organizedthemes.com Bill Robbins

      Thanks Ashfame. No wonder I couldn’t get do_shortcode() to work before that fix.

  • Steven Q

    Is there a way to notify one one email address of a new post instead of all the users? I run a large site with hundreds of authors and as the admin would like an email notification when one of them publishes a story.

    Thank you for your help!

    • http://cameronolivier.com Cam

      Yes, instead of $users in the mail($users,… add the email address you want it to mail to so ‘admin@somesite.com’ or whatnot. Also you wouldn’t need the whole bit creating the $user variable either.

      Hope that makes sense.

  • http://www.richardkotze.com Richard Kotze

    The code for the Google Docs PDF viewer shortcode was really useful thanks.
    So very simple. :)

  • Pingback: WordPress hack: Remove autolinks in comments

  • http://www.AllanandDawn.com Allan and Dawn

    great – when you are relative newbies these are the sort of tips that make a difference – especially the Twitter style “time ago” dates
    Didn’t even know that existed
    Allan and Dawn

  • http://www.wordpressoftheday.com Jamie Northrup

    Great hacks, the RSS one really helped me for one of my sites, had been using a plug-in for all my sites but it couldn’t work on one of them, but now you helped solve my issue! :)

    Thanks,
    Jamie

  • http://comluv.com Andy Bailey

    the automatically notify users of new posts trick just inspired me to write a plugin that notifies a guest blogger when their post has been approved. thanks!

  • http://www.websitelauncher.co.uk Jamie

    Love the ‘time ago’ hack. This was exactly what the doctor ordered and very timely.
    Many thanks.
    J

  • http://www.studiochris.us Chris Price

    do_shortcode() is very useful, but if you notice it not working as expected, it may be because your “shortcode” isn’t actually a shortcode. Some plugins use items that look like standard shortcodes, but they aren’t hooked into WordPress as actual shortcodes.

    To get these to work in a theme file, you can usually use the following instead of do_shortcode:

    • http://www.studiochris.us Chris Price

      Oops – the code block didn’t work above. Here it is (just wrap in PHP tags):

      echo apply_filter(‘the_content’, ‘the_shortcode_lookalike’);

      BONUS: This should also work with real shortcodes, but may be overkill.

  • http://maxim650.com Todd J. List

    I love these. Please keep sharing them! (I knew there was a reason I started following your tweets a while back.)

    Todd

  • http://www.strictlyonlinebiz.com/blog/ Udegbunam Chukwudi

    Does anyone know how to remove the dates in the comment section? I’m trying to make my blog dateless.

  • http://www.kittyperch.net Michelle Tran

    Sweet, I’ve been trying a few different plugins to remove the spam links but am giving this a try now. Thanks for the useful new wordpress hacks!

  • Pingback: How to use WordPress shortcode outside in your theme files

  • http://www.mttamborineaccommodation.com.au/ Brad

    I love the idea of linking a PDF straight to Google Doc instead of forcing a download, thanks!

  • http://coolteal.com Jason

    Very useful WordPress mods, definitely I will use some of this and improve performance of my blogs.

  • http://www.uneconn.com/ RJ45

    Great code, I like it.

  • http://www.goospoos.com Divyang

    Thumbnails in RSS feed is quite a cool idea. It will make the RSS feed more meaningful. Let’s try!

  • http://www.numawebdesign.com/ Daniel Crackower

    Is there a hack on wordpress to block certain folks who comment on you wordpress site. I have a blog where this aggravating guy keeps commenting, I don’t want to label it as spam because he is not spamming, he just post a lot of contrary stuff about my blog.

  • http://rolling-webdesign.com Theo

    Great and useful article, really handy tips !

  • http://www.hodgeman.co.nz Adrian

    Well, those are some handy tips to have bookmarked and at our disposal!

  • http://wpbloghost.com/ John Hoff – WP Blog Host

    Excellent list. I love being able to tweak WordPress and not have to use a plugin to do it.

  • http://www.smashblogtips.com fareed khan

    lovable tweaks i like the tweak of displaying thumbnails in RSS feeds, its very useful..thank you

  • http://www.electronickeyboardinfo.com Christian

    Wow, these are some really really great tweaks, it’s gonna help me improve my site, thanks and please post more!!

  • http://www.website-design-edinburgh.co.uk Kevin Thomson

    Cool – I really like the code for detecting the browser a visitor is using. Very handy!

  • http://ijophiel.com Jophiel Silvestrone

    Great list of tips! On the Google Docs PDF viewer shortcode tip, it opens the doc viewer in the same window. If you want it to open in a new window, like I did, add target=”_blank” to the code provided so it looks like this:

    function pdflink($attr, $content) {

    return ‘‘.$content.’‘;

    }

    add_shortcode(‘pdf’, ‘pdflink’);

  • http://www.aramyus.com/ kezliura

    i tried this:

    [pdf href="http://yoursite.com/linktoyour/file.pdf"]View PDF[/pdf]

    and didn’t work on my side. could you help me?

  • Mittul Chauhan

    all things are so useful and very good to know .. many thanks.