Super useful WordPress hacks and snippets

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', '', array(), null);


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('HTTP/1.1 302 Temporary Redirect');


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);
        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);
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        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()); ?>


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.

	$page_id = "YOUR PAGE-ID";
	$xml = @simplexml_load_file("".$page_id."") or die ("a lot");
	$fans = $xml->page->fan_count;
	echo $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.

$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.


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=""]


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');


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.

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

		'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 '' . 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"]


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

   $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.

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

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


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');