Super useful WordPress hacks and snippets

by Jean. 25 Comments -

For one of my last posts of the year, I have decided to share with you a list of the most exiting, useful and awesome WordPress hacks and code snippets to make your blogger life easier. Have a great read, and happy coding!

Add Google+ button to your posts automatically

Google+ is a new “social” service offered by Internet giant Google. If you want to let your visitor “plus” your post, why not adding a Google+ button to all of your entries automatically?

Simply paste the code below into your functions.php file. Once you saved the file, the Google+ button will be automatically displayed near your posts.

add_filter('the_content', 'wpr_google_plusone');
function wpr_google_plusone($content) {
	$content = $content.'<div class="plusone"><g:plusone size="tall" href="'.get_permalink().'"></g:plusone></div>';
	return $content;
}
add_action ('wp_enqueue_scripts','wpr_google_plusone_script');
function wpr_google_plusone_script() {
	wp_enqueue_script('google-plusone', 'https://apis.google.com/js/plusone.js', array(), null);
}

Source: http://www.wprecipes.com/wordpress-hook-automatically-add-a-google-button-to-your-posts

Redirect RSS feeds to Feedburner

Feedburner is a well known service that let you know how many people have subscribed to your RSS feeds. Instead of tweaking your theme to replace links to WordPress built-in feed, you should definitely use this hook which automatically redirect all WordPress feeds to your Feedburner feeds.

Edit line 4 and replace my feed url by yours. Once done, paste the code in your functions.php file. Save the file, and you’re done!

add_action('template_redirect', 'cwc_rss_redirect');
function cwc_rss_redirect() {
	if ( is_feed() && !preg_match('/feedburner|feedvalidator/i', $_SERVER['HTTP_USER_AGENT'])){
		header('Location: http://feeds.feedburner.com/catswhocode');
		header('HTTP/1.1 302 Temporary Redirect');
	}
}

Source: http://wp.smashingmagazine.com/2011/12/07/10-tips-optimize-wordpress-theme/

Track post views without using a plugin

Are you curious about how many people are reading your posts? A few “view counts” plugins exists, but here’s a simple way to do this yourself. The first thing to do is to create the functions. Paste the code below into your functions.php file.

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

Then, paste the code below within the single.php within the loop:

<?php setPostViews(get_the_ID()); ?>

Finally, paste the snippet below anywhere within the template where you would like to display the number of views:

<?php echo getPostViews(get_the_ID()); ?>

Source: http://wpsnipp.com/index.php/functions-php/track-post-views-without-a-plugin-using-post-meta/

Display number of Facebook fans in full text

If you have a Facebook page for your blog, you might want to display how many fans you have. The following snippet will display how many fans you have. Just paste it on any of your theme files, where you’d like the count to be displayed.

<?php
	$page_id = "YOUR PAGE-ID";
	$xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
	$fans = $xml->page->fan_count;
	echo $fans;
?>

Source: http://wp-snippets.com/742/display-number-facebook-fans/

Display search terms from Google

This code let you know what search terms your visitors entered before arriving to your website. Simply paste the code on any of theme files, where you’d like to display the search terms.

<?php
$refer = $_SERVER["HTTP_REFERER"];
if (strpos($refer, "google")) {
	$refer_string = parse_url($refer, PHP_URL_QUERY);
	parse_str($refer_string, $vars);
	$search_terms = $vars['q'];
	echo 'Welcome Google visitor! You searched for the following terms to get here: ';
	echo $search_terms;
};
?>

Of course, this snippet can also be used in order to log what user searched before arriving to your website.

Source: http://wp-snippets.com/820/display-search-terms-from-google-users/

Easily display external files using a shortcode

When blogging, you may sometimes need to include a file from a remote website. The following code will create a shortcode so you’ll be able to include any file you want from your WordPress post editor.

The first step is to open your functions.php file and paste the code below in it.

function show_file_func( $atts ) {
  extract( shortcode_atts( array(
    'file' => ''
  ), $atts ) );
 
  if ($file!='')
    return @file_get_contents($file);
}
 
add_shortcode( 'show_file', 'show_file_func' );

Once you saved your functions.php file, you can use the shortcode using the following syntax:

[show_file file="http://www.somesite.com/somepage.html"]

Source: http://www.prelovac.com/vladimir/wordpress-shortcode-snippet-to-display-external-files

Email contributors when their posts are published

In case you’re running a multi-author blog, it can be a good thing to let your contributors know when one of their posts are being published. The following code have to be pasted in your functions.php. Once done, an automated email will be sent to any contributors when his posts are published.

function wpr_authorNotification($post_id) {
   $post = get_post($post_id);
   $author = get_userdata($post->post_author);

   $message = "
      Hi ".$author->display_name.",
      Your post, ".$post->post_title." has just been published. Well done!
   ";
   wp_mail($author->user_email, "Your article is online", $message);
}
add_action('publish_post', 'wpr_authorNotification');

Source: http://www.wprecipes.com/how-to-automatically-email…

Display snapshots of external websites using a shortcode

Are you showcasing websites on your blog? If yes, you may find very useful to be able to put a snapshot of any website just by using a shortcode and the website url. This code, created by Ben Gillbanks and initially released as a plugin, will do the job perfectly.

Let’s start by adding the functions below into your functions.php file.

<?php
function bm_sc_mshot ($attributes, $content = '', $code = '') {

	extract(shortcode_atts(array(
		'url' => '',
		'width' => 250,
	), $attributes));

	$imageUrl = bm_mshot ($url, $width);

	if ($imageUrl == '') {
		return '';
	} else {
		$image = '<img src="' . $imageUrl . '" alt="' . $url . '" width="' . $width . '"/>';
		return '<div class="browsershot mshot"><a href="' . $url . '">' . $image . '</a></div>';
	}

}

function bm_mshot ($url = '', $width = 250) {

	if ($url != '') {
		return 'http://s.wordpress.com/mshots/v1/' . urlencode(clean_url($url)) . '?w=' . $width;
	} else {
		return '';
	}

}

add_shortcode('browsershot', 'bm_sc_mshot');
?>

Once done, you can use the [browsershot] shortcode on WordPress editor, as shown below:

[browsershot url="http://link-to-website" width="foo-value"]

Source: http://www.binarymoon.co.uk/2010/02/automated-take-screenshots-website-free/

List sites from your network

Here is another super-useful function for those running a network of websites using the features available in WordPress 3.+. Do you need to list all sites from your network? It’s actually pretty easy using the following function.

The first step is, as you can guess, to add the required functions into your theme functions.php file.

function wp_list_sites( $expires = 7200 ) {
   if( !is_multisite() ) return false;

   // Because the get_blog_list() function is currently flagged as deprecated
   // due to the potential for high consumption of resources, we'll use
   // $wpdb to roll out our own SQL query instead. Because the query can be
   // memory-intensive, we'll store the results using the Transients API
   if ( false === ( $site_list = get_transient( 'multisite_site_list' ) ) ) {
      global $wpdb;
      $site_list = $wpdb->get_results( $wpdb->prepare('SELECT * FROM wp_blogs ORDER BY blog_id') );
      // Set the Transient cache to expire every two hours
      set_site_transient( 'multisite_site_list', $site_list, $expires );
   }

   $current_site_url = get_site_url( get_current_blog_id() );

   $html = '
<ul id="network-menu">' . "\n";

   foreach ( $site_list as $site ) {
      switch_to_blog( $site->blog_id );
      $class = ( home_url() == $current_site_url ) ? ' class="current-site-item"' : '';
      $html .= "\t" . '
<li id="site-' . $site->blog_id . '" '="" .="" $class=""><a href="' . home_url() . '">' . get_bloginfo('name') . '</a></li>

' . "\n";
      restore_current_blog();
   }

   $html .= '</ul>

<!--// end #network-menu -->' . "\n\n";

   return $html;
}

Once done, the following code will display all sites from your network. Simply paste it on any of theme files, where you want the list to be displayed.

<?php
// Multisite Network Menu
$network_menu = wp_list_sites();
if( $network_menu ):
?>
<div id="network-menu">
   <?php echo $network_menu; ?>
</div>

<!--// end #network-menu -->
<?php endif; ?>

Source: http://wp.smashingmagazine.com/2011/11/17/wordpress-multisite-practical-functions-methods/

Add post class if the post has a thumbnail

When styling your theme, it can be tricky to deal with post that have a post thumbnail and those who don’t. In order to simplify yor front-end coding, you should use this code, who add a has_thumb css class to the post class.

Just paste the code below into your functions.php file.

function has_thumb_class($classes) {
	global $post;
	if( has_post_thumbnail($post->ID) ) { $classes[] = 'has_thumb'; }

		return $classes;
}
add_filter('post_class', 'has_thumb_class');

Source: http://wp-snippets.com/2178/add-post-class-if-post-has-thumbnail/

  • http://voodoopress.com Rev. Voodoo

    Great list! One thing I’ve been starting to try to guide my readers towards on VoodooPress, is differentiating what code should go in functions.php, and what code is better suited to a functionality plugin. http://vudu.me/plugin is the link (if you don’t mind me linking it). Thanks for the code!

  • http://wp-master.ru/ wpmaster

    Great collection of hacks.

    • http://www.wsd.co.il mazi

      Less hacks, more as addition to wordpress for ultimate usage.

  • http://wp-snippets.com Filip Stefansson

    Thanks for featuring my snippets, Jean-Baptiste!

  • http://blog.wasimshaikh.com Wasim Shaikh

    Very useful Article, I always want some functionality with plugins, Google+ and Visitor count is really helpful.

    Thanks for sharing.

  • http://www.itoctopus.com itoctopus

    The one that returns the number of Facebook fans is extremely useful!

    Also the one that gets the number of post views is very intelligent, using WordPress’s API to alter the table and create a new field (the count). Interesting…

  • http://hitchhackerguide.com Thorsten

    Track post views without using a plugin seems to be a good solution when you have a low amount of hits, but when you get a reasonable amount of traffic then you’d likely not update your db on every post load as it would not only invalidate caches it would also cause a db write for each of the updates.

  • http://www.dinovici.com Vic Dinovici

    Fantastic! Thanks for this useful collection of WP snippets!

    Jean-Baptiste, do you think is possible to have G+ button by default on a regular non-wp website?

    I know you can just use the snippet provided by Google itself but I just try to avoid adding new js files.

  • http://www.sixthsensemarketing.com.au/ Bradley

    Some great snippets of code, thanks!

  • http://jeffdrumgod.com.br Jeff_Drumgod

    Very good. Congratulations, and thanks for sharing that knowledge.
    I use in my personal blog that is coming :)

  • http://www.varusoft.com AdrianMaftei

    Nice and useful article. I bookmarked this link.

  • http://www.nightocoder.com Rawaf

    Great collection of hacks, really useful article.
    I found some codes that search about it
    thank you so much :)

  • http://ukwebsolutionsdirect.co.uk Paul

    The “Display search terms from Google” is a nice little hack, thanks for sharing.

  • http://www.forsberg-marketing.com Jonas

    Found an article of yours on the 30 most wanted comment hacks, and really found a lot of them awesome. Even highly considered the removal of ‘nofollow’ until I read Google wouldn’t appreciate it. And being banned from AdSense, I try to keep Google happy from now on. :P

    I just wish I knew how to do that stuff there. It’s all Ancient Greek to me.

  • http://docraptor.com/ Tyler

    Awesome post! These code snippets are so useful it makes me wonder why WordPress doesn’t simply offer them by default. Obviously the platform makes it easy to customize your own scripts, but making these (or similar code) available by default would make adding functionality to WordPress blogs a lot more accessible.

  • http://webdevelopergeeks.com webdevelopergeeks

    Hey great hacks. I have multisites and i needed it badly. listing your network sites, Mailing contributors on publishing their post all are pretty handy. Thanks a lot!!!

  • http://www.calitibus.com Simon Frandsen

    Thanks for sharing this. Some very useful information a great help for me.
    I just love WordPress : )

    Take Care
    Simon

  • http://www.xtence.be Xtence

    this is great ! thanks for sharing, so usefull man !

  • http://www.hiphopknights.com Richard Henry

    I have been reading about hacks in the past few months. This is something I can learn from. I will never be a master at it but it’s still interesting to read about.

  • http://soderlind.no PerS

    Thanks for sharing :)

    Here’s another one for your collection, how to remove ‘Comments are closed.’:

    add_filter(‘gettext’, ‘ps_remove_comments_are_closed’, 20, 3);

    function ps_remove_comments_are_closed($translated_text, $untranslated_text, $domain) {
    if ( $untranslated_text == ‘Comments are closed.’ ) {
    return ”;
    }
    return $translated_text;
    }

  • http://frisch-inspiriert.de Kai

    Thanks for sharing these great Snippets.

  • http://ipaddicas.com André Darugna

    Thanks for sharing, the last one is the best for my needs.
    Amazing, I will do some modifications for use it!

    Best regards.

  • http://www.techeverytime.com Ankur

    I got to know about this website from smashing magazine. Really useful.
    I am going to implement some of these techniques on my site. Tracking post without any plugin was useful tip for me

  • http://www.usjoomlaforce.com Rusell

    thanks for sharing this stuff.

  • http://erin2lydesign.com Erin Tooley

    These are so helpful!! Thank you for the resources!!