WordPress tip: Speed up your blog by caching custom queries

Nothing hard here: simply paste the following code where you need to execute a custom query to the database. Don’t forget to update the query on line 5!

<?php
// Get any existing copy of our transient data
if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) {
    // It wasn't there, so regenerate the data and save the transient
     $special_query_results = new WP_Query( 'cat=5&order=random&tag=tech&post_meta_key=thumbnail' );
     set_transient( 'special_query_results', $special_query_results );
}

// Use the data like you would have normally...
?>

This code is using WordPress Transients API. Click here to view more useful examples of this API!

Credits: WordPress Codex.

WordPress Transients API – Practical examples

What is the transients API, and why it’s useful

Most developers who worked with WordPress in the past probably ever heard of the Options API, which allow you to save, update and delete custom values. The Transients API is pretty similar to the Options API, but with the feature of an expiration time, which simplifies the process of using the wp_options database table to store cached information.

After you read the practical example I’ve listed on this post, I suggest you to read the Transients API page on WordPress Codex.

List sites from your network

Let’s start with an interesting snippet for those who run networks of many blogs. The code below display a general menu of all sites from your networks. In this case, transients are used to store the data for a defined time (which can be set using the $expires variable on line 1) so you’ll not make huge database calls each time your menu have to be displayed.

To use this snippet, first you have to paste the function into your 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…/

Twitter followers count using WordPress transients

Many blogs, including this one, are displaying how many people are following them on Twitter. It’s quite easy to grab some json data, but it takes a significant amount of time. Using transients allow you to grab the json data from Twitter once a day, and store it in your database for future uses.

Simply paste the function below into your functions.php file:

function my_followers_count($screen_name = 'kovshenin'){
	$key = 'my_followers_count_' . $screen_name;

	// Let's see if we have a cached version
	$followers_count = get_transient($key);
	if ($followers_count !== false)
		return $followers_count;
	else
	{
		// If there's no cached version we ask Twitter
		$response = wp_remote_get("http://api.twitter.com/1/users/show.json?screen_name={$screen_name}");
		if (is_wp_error($response))
		{
			// In case Twitter is down we return the last successful count
			return get_option($key);
		}
		else
		{
			// If everything's okay, parse the body and json_decode it
			$json = json_decode(wp_remote_retrieve_body($response));
			$count = $json->followers_count;

			// Store the result in a transient, expires after 1 day
			// Also store it as the last successful using update_option
			set_transient($key, $count, 60*60*24);
			update_option($key, $count);
			return $count;
		}
	}
}

echo "I have " . my_followers_count('kovshenin') . " followers";

→ Source: http://kovshenin.com/2010/05/twitter-followers-count-snippet-for-wordpress-2253/

RSS subscribers count using WordPress transients

Using exactly the same technique as demonstrated above, we can grab RSS subscribers and store the result in WordPress database. Don’t forget to update the code with your own feedburner url on line 2. Then, paste the code where you’d like to display how many RSS feed readers you have.

function feed_subscribers(){
        $feed_url = 'http://feeds.feedburner.com/yourname';
        $count = get_transient('feed_count');
        if ($count != false) return $count;
	$count = 0;
        $data  = wp_remote_get('http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri='.$feed_url.'');
   if (is_wp_error($data)) {
        return 'error';
   }else{
	$body = wp_remote_retrieve_body($data);
	$xml = new SimpleXMLElement($body);
	$status = $xml->attributes();
	if ($status == 'ok') {
		$count = $xml->feed->entry->attributes()->circulation;
	} else {
		$count = 300; // fallback number
	}
   }
	set_transient('feed_count', $count, 60*60*24); // 24 hour cache
	echo $count;
}

→ Source: https://wpsnipp.com/index.php/functions-php/get-feedburner-count-using-get_transient-and-wp_remote_get/

Cached navigation menu

Introduced in WordPress 3.0, the new menu system is definitely an improvement to WordPress. But using transients, we can even do something better, a menu with the same functionality but without the huge database requests.

<?php
/**
 * Wrapper function around wp_nav_menu() that will cache the wp_nav_menu for all tag/category
 * pages used in the nav menus
 * @see http://lookup.hitchhackerguide.com/wp_nav_menu for $args
 * @author tott
 */ 
function hh_cached_nav_menu( $args = array(), $prime_cache = false ) {
	global $wp_query;

	$queried_object_id = empty( $wp_query->queried_object_id ) ? 0 : (int) $wp_query->queried_object_id;

	// If design of navigation menus differs per queried object use the key below
	// $nav_menu_key = md5( serialize( $args ) . '-' . $queried_object_id );

	// Otherwise
	$nav_menu_key = md5( serialize( $args ) );

	$my_args = wp_parse_args( $args );
	$my_args = apply_filters( 'wp_nav_menu_args', $my_args );
	$my_args = (object) $my_args;

	if ( ( isset( $my_args->echo ) && true === $my_args->echo ) || !isset( $my_args->echo ) ) {
		$echo = true;
	} else {
		$echo = false;
	}

	$skip_cache = false;
	$use_cache = ( true === $prime_cache ) ? false : true;

	// If design of navigation menus differs per queried object comment out this section
	//*
	if ( is_singular() ) {
		$skip_cache = true;
	} else if ( !in_array( $queried_object_id, hh_get_nav_menu_cache_objects( $use_cache ) ) ) {
		$skip_cache = true;
	}
	//*/

	if ( true === $skip_cache || true === $prime_cache || false === ( $nav_menu = get_transient( $nav_menu_key ) ) ) {
		if ( false === $echo ) {
			$nav_menu = wp_nav_menu( $args );
		} else {
			ob_start();
			wp_nav_menu( $args );
			$nav_menu = ob_get_clean();
		}
		if ( false === $skip_cache )
			set_transient( $nav_menu_key, $nav_menu );
	} 
	if ( true === $echo )
		echo $nav_menu;
	else
		return $nav_menu;
}

/**
 * Invalidate navigation menu when an update occurs
 */
function hh_update_nav_menu_objects( $menu_id = null, $menu_data = null ) {
	hh_cached_nav_menu( array( 'echo' => false ), $prime_cache = true );
}
add_action( 'wp_update_nav_menu', 'hh_update_nav_menu_objects' );

/** 
 * Helper function that returns the object_ids we'd like to cache
 */
function hh_get_nav_menu_cache_objects( $use_cache = true ) {
	$object_ids = get_transient( 'hh_nav_menu_cache_object_ids' );
	if ( true === $use_cache && !empty( $object_ids ) ) {
		return $object_ids;
	}

	$object_ids = $objects = array();

	$menus = wp_get_nav_menus();
	foreach ( $menus as $menu_maybe ) {
		if ( $menu_items = wp_get_nav_menu_items( $menu_maybe->term_id ) ) {
			foreach( $menu_items as $menu_item ) {
				if ( preg_match( "#.*/category/([^/]+)/?$#", $menu_item->url, $match ) )
					$objects['category'][] = $match[1];
				if ( preg_match( "#.*/tag/([^/]+)/?$#", $menu_item->url, $match ) )
					$objects['post_tag'][] = $match[1];
			}
		}
	}
	if ( !empty( $objects ) ) {
		foreach( $objects as $taxonomy => $term_names ) {
			foreach( $term_names as $term_name ) {
				$term = get_term_by( 'slug', $term_name, $taxonomy );
				if ( $term )
					$object_ids[] = $term->term_id;
			}
		}
	}

	$object_ids[] = 0; // that's for the homepage

	set_transient( 'hh_nav_menu_cache_object_ids', $object_ids );
	return $object_ids;
}

→ Source: http://hitchhackerguide.com/2011/10/07/caching-wordpress-navigation-menus-wp_nav_menu-wrapper/

Cached Tag cloud

Thanks to WordPress transients API, caching almost anything is definitely. The following example shows how to cache the good old tag cloud. Simply paste this code wherever you want you tag cloud to be displayed.

$tag_cloud = get_transient( 'tag_cloud' );
if ( false === $tag_cloud || '' === $tag_cloud ){
	$args = array('echo' => false);
	$tag_cloud = wp_tag_cloud( $args );
	set_transient( 'tag_cloud', $tag_cloud, 60*60*12 );
}
echo $tag_cloud;

→ Source: http://wpengineer.com/2148/simple-cache-with-the-wordpress-transient-api/

Caching any custom query using transients

Is your theme using custom queries? If yes, you should definitely use the transients API to cache the queries. The following code shows how to cache a custom query. As you can see, there’s nothing complicated at all.

<?php
// Get any existing copy of our transient data
if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) {
    // It wasn't there, so regenerate the data and save the transient
     $special_query_results = new WP_Query( 'cat=5&order=random&tag=tech&post_meta_key=thumbnail' );
     set_transient( 'special_query_results', $special_query_results );
}

// Use the data like you would have normally...
?>

→ Source: http://codex.wordpress.org/Transients_API

10 super useful PHP snippets you probably haven’t seen

Text messaging with PHP using the TextMagic API

If for some reason, you need to send text messages to your clients cell phones, you should definitely have a look to TextMagic. They provide an easy API which allow you to send SMS to cell phones. Please note that the TextMagic service isn’t free.

The example below shows how easy it is to send a SMS to a cell phone using the TextMagic API:

// Include the TextMagic PHP lib
require('textmagic-sms-api-php/TextMagicAPI.php');

// Set the username and password information
$username = 'myusername';
$password = 'mypassword';

// Create a new instance of TM
$router = new TextMagicAPI(array(
	'username' => $username,
	'password' => $password
));

// Send a text message to '999-123-4567'
$result = $router->send('Wake up!', array(9991234567), true);

// result:  Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )

Source: http://davidwalsh.name/php-text-messaging

Detect location by IP

Here is an useful code snippet to detect the location of a specific IP. The function below takes one IP as a parameter, and returns the location of the IP. If no location is found, UNKNOWN is returned.

function detect_city($ip) {

        $default = 'UNKNOWN';

        if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
            $ip = '8.8.8.8';

        $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';

        $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
        $ch = curl_init();

        $curl_opt = array(
            CURLOPT_FOLLOWLOCATION  => 1,
            CURLOPT_HEADER      => 0,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_USERAGENT   => $curlopt_useragent,
            CURLOPT_URL       => $url,
            CURLOPT_TIMEOUT         => 1,
            CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],
        );

        curl_setopt_array($ch, $curl_opt);

        $content = curl_exec($ch);

        if (!is_null($curl_info)) {
            $curl_info = curl_getinfo($ch);
        }

        curl_close($ch);

        if ( preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs) )  {
            $city = $regs[1];
        }
        if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) )  {
            $state = $regs[1];
        }

        if( $city!='' && $state!='' ){
          $location = $city . ', ' . $state;
          return $location;
        }else{
          return $default;
        }

    }

Source: http://snipplr.com/view/48386/detect-location-by-ip-city-state/

Display source code of any webpage

Want to be able to display the source code of any webpage, with line numbering? Here is a simple code snippet to do it. Just modify the url on line 2 at your convenience. Or even better, make a pretty function according to your needs.

<?php // display source code
$lines = file('http://google.com/');
foreach ($lines as $line_num => $line) {
	// loop thru each line and prepend line numbers
	echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";
}

Source: http://perishablepress.com/code-snippets/#code-snippets_php

Check if server is HTTPS

Is my script running on a HTTPS server? Good question. This handy snippet can give you the answer. Nothing complicated at all!

if ($_SERVER['HTTPS'] != "on") {
	echo "This is not HTTPS";
}else{
	echo "This is HTTPS";
}

Source: http://snipplr.com/view/62373/check-if-url-is-https-in-php/

Display Facebook fans count in full text

Want to display how many Facebook fans do you have, in full text, on your blog? It’s very easy using the following snippet:

function fb_fan_count($facebook_name){
    // Example: https://graph.facebook.com/digimantra
    $data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
    echo $data->likes;
}

Source: http://www.digimantra.com/

Determine the dominant color of an image

This code will be super useful for people managing images or photography website. With it, you can analyze any image and get its dominant color (R, G, or B).

$i = imagecreatefromjpeg("image.jpg");

for ($x=0;$x<imagesx($i);$x++) {
    for ($y=0;$y<imagesy($i);$y++) {
        $rgb = imagecolorat($i,$x,$y);
        $r   = ($rgb >> 16) & 0xFF;
        $g   = ($rgb >>  & 0xFF;
        $b   = $rgb & 0xFF;

        $rTotal += $r;
        $gTotal += $g;
        $bTotal += $b;
        $total++;
    }
}

$rAverage = round($rTotal/$total);
$gAverage = round($gTotal/$total);
$bAverage = round($bTotal/$total);

Source: http://forums.devnetwork.net/viewtopic.php?t=39594

Get info about your memory usage

In order to optimize your scripts, you may definitely want to know how many amount of RAM they use on your server. This snippet will check memory and then print initial, final and peak usages.

echo "Initial: ".memory_get_usage()." bytes \n";
/* prints
Initial: 361400 bytes
*/

// let's use up some memory
for ($i = 0; $i < 100000; $i++) {
	$array []= md5($i);
}

// let's remove half of the array
for ($i = 0; $i < 100000; $i++) {
	unset($array[$i]);
}

echo "Final: ".memory_get_usage()." bytes \n";
/* prints
Final: 885912 bytes
*/

echo "Peak: ".memory_get_peak_usage()." bytes \n";
/* prints
Peak: 13687072 bytes
*/

Source: http://net.tutsplus.com/tutorials/php/9-useful-php…

Compress data using gzcompress()

When working with strings, it is not rare that some are very long. Using the gzcompress() function, strings can be compressed. To uncompressed it, simply call the gzuncompress() function as demonstrated below:

$string =
"Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nunc ut elit id mi ultricies
adipiscing. Nulla facilisi. Praesent pulvinar,
sapien vel feugiat vestibulum, nulla dui pretium orci,
non ultricies elit lacus quis ante. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Aliquam
pretium ullamcorper urna quis iaculis. Etiam ac massa
sed turpis tempor luctus. Curabitur sed nibh eu elit
mollis congue. Praesent ipsum diam, consectetur vitae
ornare a, aliquam a nunc. In id magna pellentesque
tellus posuere adipiscing. Sed non mi metus, at lacinia
augue. Sed magna nisi, ornare in mollis in, mollis
sed nunc. Etiam at justo in leo congue mollis.
Nullam in neque eget metus hendrerit scelerisque
eu non enim. Ut malesuada lacus eu nulla bibendum
id euismod urna sodales. ";

$compressed = gzcompress($string);

echo "Original size: ". strlen($string)."\n";
/* prints
Original size: 800
*/

echo "Compressed size: ". strlen($compressed)."\n";
/* prints
Compressed size: 418
*/

// getting it back
$original = gzuncompress($compressed);

Source: http://net.tutsplus.com/tutorials/php/9-useful-php…

Whois query using PHP

If you need to get the whois information for a specific domain, why not using PHP to do it? The following function take a domain name as a parameter, and then display the whois info related to the domain.

function whois_query($domain) {

    // fix the domain name:
    $domain = strtolower(trim($domain));
    $domain = preg_replace('/^http:\/\//i', '', $domain);
    $domain = preg_replace('/^www\./i', '', $domain);
    $domain = explode('/', $domain);
    $domain = trim($domain[0]);

    // split the TLD from domain name
    $_domain = explode('.', $domain);
    $lst = count($_domain)-1;
    $ext = $_domain[$lst];

    // You find resources and lists
    // like these on wikipedia:
    //
    // http://de.wikipedia.org/wiki/Whois
    //
    $servers = array(
        "biz" => "whois.neulevel.biz",
        "com" => "whois.internic.net",
        "us" => "whois.nic.us",
        "coop" => "whois.nic.coop",
        "info" => "whois.nic.info",
        "name" => "whois.nic.name",
        "net" => "whois.internic.net",
        "gov" => "whois.nic.gov",
        "edu" => "whois.internic.net",
        "mil" => "rs.internic.net",
        "int" => "whois.iana.org",
        "ac" => "whois.nic.ac",
        "ae" => "whois.uaenic.ae",
        "at" => "whois.ripe.net",
        "au" => "whois.aunic.net",
        "be" => "whois.dns.be",
        "bg" => "whois.ripe.net",
        "br" => "whois.registro.br",
        "bz" => "whois.belizenic.bz",
        "ca" => "whois.cira.ca",
        "cc" => "whois.nic.cc",
        "ch" => "whois.nic.ch",
        "cl" => "whois.nic.cl",
        "cn" => "whois.cnnic.net.cn",
        "cz" => "whois.nic.cz",
        "de" => "whois.nic.de",
        "fr" => "whois.nic.fr",
        "hu" => "whois.nic.hu",
        "ie" => "whois.domainregistry.ie",
        "il" => "whois.isoc.org.il",
        "in" => "whois.ncst.ernet.in",
        "ir" => "whois.nic.ir",
        "mc" => "whois.ripe.net",
        "to" => "whois.tonic.to",
        "tv" => "whois.tv",
        "ru" => "whois.ripn.net",
        "org" => "whois.pir.org",
        "aero" => "whois.information.aero",
        "nl" => "whois.domain-registry.nl"
    );

    if (!isset($servers[$ext])){
        die('Error: No matching nic server found!');
    }

    $nic_server = $servers[$ext];

    $output = '';

    // connect to whois server:
    if ($conn = fsockopen ($nic_server, 43)) {
        fputs($conn, $domain."\r\n");
        while(!feof($conn)) {
            $output .= fgets($conn,128);
        }
        fclose($conn);
    }
    else { die('Error: Could not connect to ' . $nic_server . '!'); }

    return $output;
}

Source: http://www.jonasjohn.de/snippets/php/whois-query.htm

Email PHP errors instead of displaying it

By default, most servers are set to display an error message when an error occured in one of your script. For security reasons, you may want to get an email with the error, instead of displaying it to the public.

<?php

// Our custom error handler
function nettuts_error_handler($number, $message, $file, $line, $vars){
	$email = "
		<p>An error ($number) occurred on line
		<strong>$line</strong> and in the <strong>file: $file.</strong>
		<p> $message </p>";

	$email .= "<pre>" . print_r($vars, 1) . "</pre>";

	$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

	// Email the error to someone...
	error_log($email, 1, '[email protected]', $headers);

	// Make sure that you decide how to respond to errors (on the user's side)
	// Either echo an error message, or kill the entire project. Up to you...
	// The code below ensures that we only "die" if the error was more than
	// just a NOTICE.
	if ( ($number !== E_NOTICE) && ($number < 2048) ) {
		die("There was an error. Please try again later.");
	}
}

// We should use our custom function to handle errors.
set_error_handler('nettuts_error_handler');

// Trigger an error... (var doesn't exist)
echo $somevarthatdoesnotexist;

Source: http://net.tutsplus.com/tutorials/php/quick-tip…

WordPress: Improved the_excerpt() function

The first thing to do is to create the function. Open your functions.php file and paste the code below in it.

// Variable & intelligent excerpt length.
function print_excerpt($length) { // Max excerpt length. Length is set in characters
	global $post;
	$text = $post->post_excerpt;
	if ( '' == $text ) {
		$text = get_the_content('');
		$text = apply_filters('the_content', $text);
		$text = str_replace(']]>', ']]>', $text);
	}
	$text = strip_shortcodes($text); // optional, recommended
	$text = strip_tags($text); // use ' $text = strip_tags($text,'<p><a>'); ' if you want to keep some tags

	$text = substr($text,0,$length);
	$excerpt = reverse_strrchr($text, '.', 1);
	if( $excerpt ) {
		echo apply_filters('the_excerpt',$excerpt);
	} else {
		echo apply_filters('the_excerpt',$text);
	}
}

// Returns the portion of haystack which goes until the last occurrence of needle
function reverse_strrchr($haystack, $needle, $trail) {
    return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}

Once done, you can use the print_excerpt() function in your theme files, as shown below:

<?php print_excerpt(50); ?>

Thanks to Sebastian for the function!

WordPress hack: How to build a network navigation menu

The first thing to do is to create the function. Paste the code below into your functions.php file:

/**
 * Build a list of all websites in a network
 */
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, you can use the wp_list_sites() function in your theme files. The example below shows how it works:

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

Thanks to Kevin Leary for the great hack!

Tutorials and snippets to get started with CoffeeScript

What is CoffeeScript?

To keep it simple, CoffeeScript is a little language that compiles into JavaScript. If you ever coded in languages such as Python or Ruby, you’ll probably love CoffeeScript a lot. Instead of awkward braces and semicolons, JavaScript has always had a gorgeous object model at its heart.

The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime. You can use any existing JavaScript library seamlessly from CoffeeScript (and vice-versa). The compiled output is readable and pretty-printed, passes through JavaScript Lint without warnings, will work in every JavaScript implementation, and tends to run as fast or faster than the equivalent handwritten JavaScript.

Installing CoffeeScript

Installing CoffeeScript is not hard at all. The first thing to do is to make sure that you already installed a working copy of the latest stable version of Node.js as well as npm, the Node Package Manager.

Once done, you can install CoffeeScript by running the following command:

npm install -g coffee-script

CoffeeScript is now installed. Next step is to compile a .coffee file into a .js file. Use the following syntax to do so:

coffee --compile example.coffee

CoffeeScript.org is the official website of the CoffeeScript language. Don’t hesitate to visit it, it’s full of helpful ressources.

Tutorial: Basics of CoffeeScript


A great tutorial that demonstrate all you need to get started with CoffeeScript: installation, configuration and first lines of codes.
View tutorial

Tutorial: Rocking out with CoffeeScript


A very complete tutorial that will make you a real CoffeeScript coder: it will show you how to write your code, how to indent, how to use classes, conditionnal statements and more.
View tutorial

Tutorial: Creating an iOS-like Home Screen with CoffeeScript


Now, let’s code something concrete: this tutorial will show you how to create an iOS-like home screen, using CoffeeScript. A great way to learn by the example.
View tutorial

CoffeeScript snippet: Shorten url using Google’s Goo.gl service

Short urls are very useful, especially on social networking sites like Twitter. Want to be able to create your own short urls using Google goo;gl service? No problem, just use the following code. Please note that you’ll need your own Google API key for the code to work.

apikey = "YOUR GOOGLE API KEY GOES HERE"

shorten_url = (url, success_callback, error_callback) ->

  xhr = Titanium.Network.createHTTPClient()
  xhr.open "POST", "https://www.googleapis.com/urlshortener/v1/url?key=" + apikey
  xhr.setRequestHeader "Content-type", "application/json"
  xhr.onload = () -> success_callback xhr.status, xhr.responseText
  xhr.onerror = () -> error_callback xhr.status, xhr.responseText
  content =  "{\"longUrl\": \"#{url}\"}"
  xhr.send content

→ Source: http://developer.appcelerator.com/question/125880/…

CoffeScript snippet: Read in a file

CoffeeScript make reading files very easy, as shown below:

fs.readFile 'data.txt', (err, data) -> fileText = data

→ Source: http://ricardo.cc/2011/06/02/10-CoffeeScript-One-Liners-to-Impress-Your-Friends.html

CoffeScript snippet: Fetch and Parse a XML web service

Fetching and parsing XML or .json files from web services is quite common when coding modern web applications. Here is how you can do it using CoffeeScript:

request.get { uri:'path/to/api.json', json: true }, (err, r, body) -> results = body

→ Source: http://ricardo.cc/2011/06/02/10-CoffeeScript-One-Liners-to-Impress-Your-Friends.html

CoffeeScript snippet: Finding substrings

Another very common task, made easier with CoffeeScript:

message = "This is a test string. This has a repeat or two. This might even have a third."
message.indexOf "This", 0

→ Source: http://coffeescriptcookbook.com/chapters/strings/finding-substrings

How to rearrange WordPress categories order

The code above will look for a specific category (Don’t forget to update line 5) and will replace it on top of all other categories. The code has to be pasted in your functions.php file.

<?php
$categories = get_terms('books_category');

for( $i=0; $i<sizeof($categories); $i++ ){
  if ( $categories[$i]->name == 'New Publications' ) :
    $latest = array($categories[$i]);
    unset($categories[$i]);
  endif;
}

if( isset($latest) )
  array_splice( $categories, 0, 0, $latest );
?>

Thanks to WP Snippets for the great hack!

JavaScript frameworks, tools and techniques to create killer applications

Ofmlabs Codecs: Pure JavaScript audio decoding


Ofmlabs is bringing audio decoding to JavaScript with two great pieces of code. The first, named JSMad, was the first proof that JS audio decoding is possible and is a port of libmad, a C based MPEG audio decoder.
The second file, ALAC.js is a port of the recently open sourced Apple Lossless decoder to JavaScript. Now it is possible to play MP3 and Apple Lossless even in browsers without native support.
→ Visit Ofmlabs Codecs

Popcorn.js


Brought to you by Mozilla, Popcorn.js is an event system for HTML5 media developers. Think jQuery for video. You can leave the heavy lifting to Popcorn, and concentrate on what you do best: writing awesome code.
→ Visit Popcorn.js

JSZip: Create .zip files with JavaScript


JavaScript today is capable of generating a lot of data. The easiest way to deliver multiple files to your users is in a zip file. Instead of wasting server resources and bandwidth you can get the client to do it for you.

Is it simple and easy, you ask? Yes, definitely. Look at the example code below:

zip = new JSZip();
zip.add("Hello.", "hello.txt");
Downloadify.create('downloadify',{
...
  data: function(){
    return zip.generate();
  },
...
  dataType: 'base64'
});

→ Visit JSZip

Money.js: JavaScript currency converter


Currency conversion is a recurrent task in many businessses, but it’s not that easy to automate as everyday currencies are fluctuating. This lightweight JavaScript library can do the hard work for you. A great find!
→ Visit Money.js

Resizable videos with fitvids.js


Last year, responsible web design was a very popular new concept among web developers and designers. fitvids.js is a jQuery plugin that allow fluid width video embeds. A great tools for all responsible websites.
→ Visit fitvids.js

Generate pdf files with pdfkit for node.js


PDFKit is a PDF document generation library for Node.js written in CoffeeScript(but you can choose to use classic JavaScript of course). A very cool API for those already using server-side JavaScript to build their apps!
→ Visit pdfkit

Impress.js:


Impress.js is a presentation tool inspired by the idea behind prezi.com and based on the power of CSS3 transforms and transitions in modern browsers. This handy JavaScript file will transform your web browser into a very powerful presentation tool. Who still need programs like Powerpoint, really?
→ Visit impress.js

Display number of Facebook fans in full text on your WordPress blog

Simply paste the following code in any of your theme files, where you want your Facebook fan count to be displayed. Don’t forget to add your page ID on line 2!

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

Thanks to WP Snippets for the recipe!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

Display number of Facebook fans in full text on your WordPress blog

Super useful WordPress hacks and snippets

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/

WordPress tip: Increased height of the excerpt field

Simply paste the following code into your functions.php file. Height can be adjusted on line 5.

add_action('admin_head', 'excerpt_textarea_height');
function excerpt_textarea_height() {
    echo'
    <style type="text/css">
        #excerpt{ height:500px; }
    </style>
    ';
}

Thanks to Spyre Studios for the cool hack!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress tip: Increased height of the excerpt field

WordPress hook: Automatically add a Google+ button to your posts

Open your functions.php file and paste the following code in it:

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

Once saved, a Google+ button will be automatically added to all your posts.

Thanks to Spyre Studios for the great piece of code!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress hook: Automatically add a Google+ button to your posts

WordPress tip: Restrict user access to specific templates

Simply create a new page template and paste the following at the very beginning of the file:

<?php
/* Template Name: Restricted to Authors only */

if ( !current_user_can('author')) {
	wp_die('You don’t have access to this page.')
}
?>

Thanks to Kevin Chard for this snippet!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress tip: Restrict user access to specific templates

WordPress tip: Display informations about your multisite install

To display information about your network, simply paste the following piece of code where you want the info to be shown, for example in your theme footer.

<?php if( is_multisite() ): ?>

   The <a href="<?php echo esc_url( get_site_option( 'siteurl' ) ); ?>"><?php echo esc_html( get_site_option( 'site_name' ) ); ?> network</a> currently powers <strong><?php echo get_blog_count(); ?></strong> websites and <strong><?php echo get_user_count(); ?></strong> users.

<?php endif; ?>

Once you saved the file, your blog network name as well as the user/blogs count will be displayed.

Thanks to Kevin Leary for the cool tip!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress tip: Display informations about your multisite install