<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>CatsWhoCode.com</title>
	
	<link>http://www.catswhocode.com/blog</link>
	<description>Web Development Blog</description>
	<lastBuildDate>Mon, 23 Jan 2012 15:04:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Catswhocode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="catswhocode" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">Catswhocode</feedburner:emailServiceId><feedburner:feedburnerHostname xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>WordPress Transients API – Practical examples</title>
		<link>http://www.catswhocode.com/blog/wordpress-transients-api-practical-examples</link>
		<comments>http://www.catswhocode.com/blog/wordpress-transients-api-practical-examples#comments</comments>
		<pubDate>Mon, 23 Jan 2012 15:04:54 +0000</pubDate>
		<dc:creator>Jean-Baptiste Jung</dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://www.catswhocode.com/blog/?p=4688</guid>
		<description><![CDATA[The WordPress Transients API is a very useful tool which allow developers to cache data such as the result of a query for future uses. In this article, I've compiled a list of useful practical example to div into the power of WordPress Transients API. ]]></description>
			<content:encoded><![CDATA[<h2>What is the transients API, and why it&#8217;s useful</h2>
<p>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 <code>wp_options</code> database table to store cached information.</p>
<p>After you read the practical example I&#8217;ve listed on this post, I suggest you to read the <a href="http://codex.wordpress.org/Transients_API">Transients API  page</a> on WordPress Codex.</p>
<h2>List sites from your network</h2>
<p>Let&#8217;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 <code>$expires</code> variable on line 1) so you&#8217;ll not make huge database calls each time your menu have to be displayed.</p>
<p>To use this snippet, first you have to paste the function into your <code>functions.php</code> file. </p>
<pre>
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&#39;ll use
   // $wpdb to roll out our own SQL query instead. Because the query can be
   // memory-intensive, we&#39;ll store the results using the Transients API
   if ( false === ( $site_list = get_transient( &#39;multisite_site_list&#39; ) ) ) {
      global $wpdb;
      $site_list = $wpdb-&gt;get_results( $wpdb-&gt;prepare(&#39;SELECT * FROM wp_blogs ORDER BY blog_id&#39;) );
      // Set the Transient cache to expire every two hours
      set_site_transient( &#39;multisite_site_list&#39;, $site_list, $expires );
   }

   $current_site_url = get_site_url( get_current_blog_id() );

   $html = &#39;
&lt;ul id=&quot;network-menu&quot;&gt;&#39; . &quot;\n&quot;;

   foreach ( $site_list as $site ) {
      switch_to_blog( $site-&gt;blog_id );
      $class = ( home_url() == $current_site_url ) ? &#39; class=&quot;current-site-item&quot;&#39; : &#39;&#39;;
      $html .= &quot;\t&quot; . &#39;
&lt;li id=&quot;site-&#39; . $site-&gt;blog_id . &#39;&quot; &#39;=&quot;&quot; .=&quot;&quot; $class=&quot;&quot;&gt;&lt;a href=&quot;&#39; . home_url() . &#39;&quot;&gt;&#39; . get_bloginfo(&#39;name&#39;) . &#39;&lt;/a&gt;&lt;/li&gt;

&#39; . &quot;\n&quot;;
      restore_current_blog();
   }

   $html .= &#39;&lt;/ul&gt;

&lt;!--// end #network-menu --&gt;&#39; . &quot;\n\n&quot;;

   return $html;
}
</pre>
<p>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.</p>
<pre>
&lt;?php
// Multisite Network Menu
$network_menu = wp_list_sites();
if( $network_menu ):
?&gt;
&lt;div id=&quot;network-menu&quot;&gt;
   &lt;?php echo $network_menu; ?&gt;
&lt;/div&gt;

&lt;!--// end #network-menu --&gt;
&lt;?php endif; ?&gt;
</pre>
<p><strong>&rarr; Source: <a href="http://wp.smashingmagazine.com/2011/11/17/wordpress-multisite-practical-functions-methods/">http://wp.smashingmagazine.com/2011/11/17/wordpress&#8230;/</a></strong></p>
<h2>Twitter followers count using WordPress transients</h2>
<p>Many blogs, including this one, are displaying how many people are following them on Twitter. It&#8217;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.</p>
<p>Simply paste the function below into your <code>functions.php</code> file: </p>
<pre>
function my_followers_count($screen_name = &#39;kovshenin&#39;){
	$key = &#39;my_followers_count_&#39; . $screen_name;

	// Let&#39;s see if we have a cached version
	$followers_count = get_transient($key);
	if ($followers_count !== false)
		return $followers_count;
	else
	{
		// If there&#39;s no cached version we ask Twitter
		$response = wp_remote_get(&quot;http://api.twitter.com/1/users/show.json?screen_name={$screen_name}&quot;);
		if (is_wp_error($response))
		{
			// In case Twitter is down we return the last successful count
			return get_option($key);
		}
		else
		{
			// If everything&#39;s okay, parse the body and json_decode it
			$json = json_decode(wp_remote_retrieve_body($response));
			$count = $json-&gt;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 &quot;I have &quot; . my_followers_count(&#39;kovshenin&#39;) . &quot; followers&quot;;
</pre>
<p><strong>&rarr; Source: <a href="http://kovshenin.com/2010/05/twitter-followers-count-snippet-for-wordpress-2253/">http://kovshenin.com/2010/05/twitter-followers-count-snippet-for-wordpress-2253/</a></strong></p>
<h2>RSS subscribers count using WordPress transients</h2>
<p>Using exactly the same technique as demonstrated above, we can grab RSS subscribers and store the result in WordPress database. Don&#8217;t forget to update the code with your own feedburner url on line 2. Then, paste the code where you&#8217;d like to display how many RSS feed readers you have. </p>
<pre>
function feed_subscribers(){
        $feed_url = &#39;http://feeds.feedburner.com/yourname&#39;;
        $count = get_transient(&#39;feed_count&#39;);
        if ($count != false) return $count;
	$count = 0;
        $data  = wp_remote_get(&#39;http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=&#39;.$feed_url.&#39;&#39;);
   if (is_wp_error($data)) {
        return &#39;error&#39;;
   }else{
	$body = wp_remote_retrieve_body($data);
	$xml = new SimpleXMLElement($body);
	$status = $xml-&gt;attributes();
	if ($status == &#39;ok&#39;) {
		$count = $xml-&gt;feed-&gt;entry-&gt;attributes()-&gt;circulation;
	} else {
		$count = 300; // fallback number
	}
   }
	set_transient(&#39;feed_count&#39;, $count, 60*60*24); // 24 hour cache
	echo $count;
}
</pre>
<p><strong>&rarr; Source: <a href="https://wpsnipp.com/index.php/functions-php/get-feedburner-count-using-get_transient-and-wp_remote_get/">https://wpsnipp.com/index.php/functions-php/get-feedburner-count-using-get_transient-and-wp_remote_get/</a></strong></p>
<h2>Cached navigation menu</h2>
<p>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.</p>
<pre>
&lt;?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-&gt;queried_object_id ) ? 0 : (int) $wp_query-&gt;queried_object_id;

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

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

	$my_args = wp_parse_args( $args );
	$my_args = apply_filters( &#39;wp_nav_menu_args&#39;, $my_args );
	$my_args = (object) $my_args;

	if ( ( isset( $my_args-&gt;echo ) &amp;&amp; true === $my_args-&gt;echo ) || !isset( $my_args-&gt;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( &#39;echo&#39; =&gt; false ), $prime_cache = true );
}
add_action( &#39;wp_update_nav_menu&#39;, &#39;hh_update_nav_menu_objects&#39; );

/** 
 * Helper function that returns the object_ids we&#39;d like to cache
 */
function hh_get_nav_menu_cache_objects( $use_cache = true ) {
	$object_ids = get_transient( &#39;hh_nav_menu_cache_object_ids&#39; );
	if ( true === $use_cache &amp;&amp; !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-&gt;term_id ) ) {
			foreach( $menu_items as $menu_item ) {
				if ( preg_match( &quot;#.*/category/([^/]+)/?$#&quot;, $menu_item-&gt;url, $match ) )
					$objects[&#39;category&#39;][] = $match[1];
				if ( preg_match( &quot;#.*/tag/([^/]+)/?$#&quot;, $menu_item-&gt;url, $match ) )
					$objects[&#39;post_tag&#39;][] = $match[1];
			}
		}
	}
	if ( !empty( $objects ) ) {
		foreach( $objects as $taxonomy =&gt; $term_names ) {
			foreach( $term_names as $term_name ) {
				$term = get_term_by( &#39;slug&#39;, $term_name, $taxonomy );
				if ( $term )
					$object_ids[] = $term-&gt;term_id;
			}
		}
	}

	$object_ids[] = 0; // that&#39;s for the homepage

	set_transient( &#39;hh_nav_menu_cache_object_ids&#39;, $object_ids );
	return $object_ids;
}
</pre>
<p><strong>&rarr; Source: <a href="http://hitchhackerguide.com/2011/10/07/caching-wordpress-navigation-menus-wp_nav_menu-wrapper/">http://hitchhackerguide.com/2011/10/07/caching-wordpress-navigation-menus-wp_nav_menu-wrapper/</a></strong></p>
<h2>Cached Tag cloud</h2>
<p>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.</p>
<pre>
$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;
</pre>
<p><strong>&rarr; Source: <a href="http://wpengineer.com/2148/simple-cache-with-the-wordpress-transient-api/">http://wpengineer.com/2148/simple-cache-with-the-wordpress-transient-api/</a></strong></p>
<h2>Caching any custom query using transients</h2>
<p>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&#8217;s nothing complicated at all.</p>
<pre>
&lt;?php
// Get any existing copy of our transient data
if ( false === ( $special_query_results = get_transient( &#39;special_query_results&#39; ) ) ) {
    // It wasn&#39;t there, so regenerate the data and save the transient
     $special_query_results = new WP_Query( &#39;cat=5&amp;order=random&amp;tag=tech&amp;post_meta_key=thumbnail&#39; );
     set_transient( &#39;special_query_results&#39;, $special_query_results );
}

// Use the data like you would have normally...
?&gt;
</pre>
<p><strong>&rarr; Source: <a href="http://codex.wordpress.org/Transients_API">http://codex.wordpress.org/Transients_API</a></strong></p>
<img src="http://feeds.feedburner.com/~r/Catswhocode/~4/mWn008nUMo8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.catswhocode.com/blog/wordpress-transients-api-practical-examples/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>10 super useful PHP snippets you probably haven’t seen</title>
		<link>http://www.catswhocode.com/blog/10-super-useful-php-snippets-you-probably-havent-seen</link>
		<comments>http://www.catswhocode.com/blog/10-super-useful-php-snippets-you-probably-havent-seen#comments</comments>
		<pubDate>Mon, 16 Jan 2012 15:03:06 +0000</pubDate>
		<dc:creator>Jean-Baptiste Jung</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.catswhocode.com/blog/?p=4673</guid>
		<description><![CDATA[When working with PHP, it is very useful to have a "toolbox" of handy functions and code snippets that can save lots of time when needed. Today, I'm going to show you 10 super useful code snippets that you probably never heard of. ]]></description>
			<content:encoded><![CDATA[<h2>Text messaging with PHP using the TextMagic API</h2>
<p>If for some reason, you need to send text messages to your clients cell phones, you should definitely have a look to <a href="http://www.textmagic.com/">TextMagic</a>. They provide an easy API which allow you to send SMS to cell phones. Please note that the TextMagic service isn&#8217;t free.</p>
<p>The example below shows how easy it is to send a SMS to a cell phone using the TextMagic API:</p>
<pre>
// Include the TextMagic PHP lib
require(&#39;textmagic-sms-api-php/TextMagicAPI.php&#39;);

// Set the username and password information
$username = &#39;myusername&#39;;
$password = &#39;mypassword&#39;;

// Create a new instance of TM
$router = new TextMagicAPI(array(
	&#39;username&#39; =&gt; $username,
	&#39;password&#39; =&gt; $password
));

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

// result:  Result is: Array ( [messages] =&gt; Array ( [19896128] =&gt; 9991234567 ) [sent_text] =&gt; Wake up! [parts_count] =&gt; 1 )
</pre>
<p><strong>Source: <a href="http://davidwalsh.name/php-text-messaging">http://davidwalsh.name/php-text-messaging</a></strong></p>
<h2>Detect location by IP</h2>
<p>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, <code>UNKNOWN</code> is returned.</p>
<pre>
function detect_city($ip) {

        $default = &#39;UNKNOWN&#39;;

        if (!is_string($ip) || strlen($ip) &lt; 1 || $ip == &#39;127.0.0.1&#39; || $ip == &#39;localhost&#39;)
            $ip = &#39;8.8.8.8&#39;;

        $curlopt_useragent = &#39;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)&#39;;

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

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

        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(&#39;{&lt;li&gt;City : ([^&lt;]*)&lt;/li&gt;}i&#39;, $content, $regs) )  {
            $city = $regs[1];
        }
        if ( preg_match(&#39;{&lt;li&gt;State/Province : ([^&lt;]*)&lt;/li&gt;}i&#39;, $content, $regs) )  {
            $state = $regs[1];
        }

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

    }
</pre>
<p><strong>Source: <a href="http://snipplr.com/view/48386/detect-location-by-ip-city-state/">http://snipplr.com/view/48386/detect-location-by-ip-city-state/</a></strong></p>
<h2>Display source code of any webpage</h2>
<p>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.</p>
<pre>
&lt;?php // display source code
$lines = file(&#39;http://google.com/&#39;);
foreach ($lines as $line_num =&gt; $line) {
	// loop thru each line and prepend line numbers
	echo &quot;Line #&lt;b&gt;{$line_num}&lt;/b&gt; : &quot; . htmlspecialchars($line) . &quot;&lt;br&gt;\n&quot;;
}
</pre>
<p><strong>Source: <a href="http://perishablepress.com/code-snippets/#code-snippets_php">http://perishablepress.com/code-snippets/#code-snippets_php</a></strong></p>
<h2>Check if server is HTTPS</h2>
<p>Is my script running on a HTTPS server? Good question. This handy snippet can give you the answer. Nothing complicated at all!</p>
<pre>
if ($_SERVER[&#39;HTTPS&#39;] != &quot;on&quot;) {
	echo &quot;This is not HTTPS&quot;;
}else{
	echo &quot;This is HTTPS&quot;;
}
</pre>
<p><strong>Source: <a href="http://snipplr.com/view/62373/check-if-url-is-https-in-php/">http://snipplr.com/view/62373/check-if-url-is-https-in-php/</a></strong></p>
<h2>Display Facebook fans count in full text</h2>
<p>Want to display how many Facebook fans do you have, in full text, on your blog? It&#8217;s very easy using the following snippet:</p>
<pre>
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;
}
</pre>
<p><strong>Source: <a href="http://www.digimantra.com/">http://www.digimantra.com/</a></strong></p>
<h2>Determine the dominant color of an image</h2>
<p>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).</p>
<pre>
$i = imagecreatefromjpeg(&quot;image.jpg&quot;);

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

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

$rAverage = round($rTotal/$total);
$gAverage = round($gTotal/$total);
$bAverage = round($bTotal/$total);
</pre>
<p><strong>Source: <a href="http://forums.devnetwork.net/viewtopic.php?t=39594">http://forums.devnetwork.net/viewtopic.php?t=39594</a></strong></p>
<h2>Get info about your memory usage</h2>
<p>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.  </p>
<pre>
echo &quot;Initial: &quot;.memory_get_usage().&quot; bytes \n&quot;;
/* prints
Initial: 361400 bytes
*/

// let&#39;s use up some memory
for ($i = 0; $i &lt; 100000; $i++) {
	$array []= md5($i);
}

// let&#39;s remove half of the array
for ($i = 0; $i &lt; 100000; $i++) {
	unset($array[$i]);
}

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

echo &quot;Peak: &quot;.memory_get_peak_usage().&quot; bytes \n&quot;;
/* prints
Peak: 13687072 bytes
*/
</pre>
<p><strong>Source: <a href="http://net.tutsplus.com/tutorials/php/9-useful-php-functions-and-features-you-need-to-know/">http://net.tutsplus.com/tutorials/php/9-useful-php&#8230;</a></strong></p>
<h2>Compress data using gzcompress()</h2>
<p>When working with strings, it is not rare that some are very long. Using the <code>gzcompress()</code> function, strings can be compressed. To uncompressed it, simply call the <code>gzuncompress()</code> function as demonstrated below:</p>
<pre>
$string =
&quot;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. &quot;;

$compressed = gzcompress($string);

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

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

// getting it back
$original = gzuncompress($compressed);
</pre>
<p><strong>Source: <a href="http://net.tutsplus.com/tutorials/php/9-useful-php-functions-and-features-you-need-to-know/">http://net.tutsplus.com/tutorials/php/9-useful-php&#8230;</a></strong></p>
<h2>Whois query using PHP</h2>
<p>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.</p>
<pre>
function whois_query($domain) {

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

    // split the TLD from domain name
    $_domain = explode(&#39;.&#39;, $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(
        &quot;biz&quot; =&gt; &quot;whois.neulevel.biz&quot;,
        &quot;com&quot; =&gt; &quot;whois.internic.net&quot;,
        &quot;us&quot; =&gt; &quot;whois.nic.us&quot;,
        &quot;coop&quot; =&gt; &quot;whois.nic.coop&quot;,
        &quot;info&quot; =&gt; &quot;whois.nic.info&quot;,
        &quot;name&quot; =&gt; &quot;whois.nic.name&quot;,
        &quot;net&quot; =&gt; &quot;whois.internic.net&quot;,
        &quot;gov&quot; =&gt; &quot;whois.nic.gov&quot;,
        &quot;edu&quot; =&gt; &quot;whois.internic.net&quot;,
        &quot;mil&quot; =&gt; &quot;rs.internic.net&quot;,
        &quot;int&quot; =&gt; &quot;whois.iana.org&quot;,
        &quot;ac&quot; =&gt; &quot;whois.nic.ac&quot;,
        &quot;ae&quot; =&gt; &quot;whois.uaenic.ae&quot;,
        &quot;at&quot; =&gt; &quot;whois.ripe.net&quot;,
        &quot;au&quot; =&gt; &quot;whois.aunic.net&quot;,
        &quot;be&quot; =&gt; &quot;whois.dns.be&quot;,
        &quot;bg&quot; =&gt; &quot;whois.ripe.net&quot;,
        &quot;br&quot; =&gt; &quot;whois.registro.br&quot;,
        &quot;bz&quot; =&gt; &quot;whois.belizenic.bz&quot;,
        &quot;ca&quot; =&gt; &quot;whois.cira.ca&quot;,
        &quot;cc&quot; =&gt; &quot;whois.nic.cc&quot;,
        &quot;ch&quot; =&gt; &quot;whois.nic.ch&quot;,
        &quot;cl&quot; =&gt; &quot;whois.nic.cl&quot;,
        &quot;cn&quot; =&gt; &quot;whois.cnnic.net.cn&quot;,
        &quot;cz&quot; =&gt; &quot;whois.nic.cz&quot;,
        &quot;de&quot; =&gt; &quot;whois.nic.de&quot;,
        &quot;fr&quot; =&gt; &quot;whois.nic.fr&quot;,
        &quot;hu&quot; =&gt; &quot;whois.nic.hu&quot;,
        &quot;ie&quot; =&gt; &quot;whois.domainregistry.ie&quot;,
        &quot;il&quot; =&gt; &quot;whois.isoc.org.il&quot;,
        &quot;in&quot; =&gt; &quot;whois.ncst.ernet.in&quot;,
        &quot;ir&quot; =&gt; &quot;whois.nic.ir&quot;,
        &quot;mc&quot; =&gt; &quot;whois.ripe.net&quot;,
        &quot;to&quot; =&gt; &quot;whois.tonic.to&quot;,
        &quot;tv&quot; =&gt; &quot;whois.tv&quot;,
        &quot;ru&quot; =&gt; &quot;whois.ripn.net&quot;,
        &quot;org&quot; =&gt; &quot;whois.pir.org&quot;,
        &quot;aero&quot; =&gt; &quot;whois.information.aero&quot;,
        &quot;nl&quot; =&gt; &quot;whois.domain-registry.nl&quot;
    );

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

    $nic_server = $servers[$ext];

    $output = &#39;&#39;;

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

    return $output;
}
</pre>
<p><strong>Source: <a href="http://www.jonasjohn.de/snippets/php/whois-query.htm">http://www.jonasjohn.de/snippets/php/whois-query.htm</a></strong></p>
<h2>Email PHP errors instead of displaying it</h2>
<p>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.</p>
<pre>
&lt;?php

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

	$email .= &quot;&lt;pre&gt;&quot; . print_r($vars, 1) . &quot;&lt;/pre&gt;&quot;;

	$headers = &#39;Content-type: text/html; charset=iso-8859-1&#39; . &quot;\r\n&quot;;

	// Email the error to someone...
	error_log($email, 1, &#39;you@youremail.com&#39;, $headers);

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

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

// Trigger an error... (var doesn&#39;t exist)
echo $somevarthatdoesnotexist;
</pre>
<p><strong>Source: <a href="http://net.tutsplus.com/tutorials/php/quick-tip-email-error-logs-to-yourself-with-php/">http://net.tutsplus.com/tutorials/php/quick-tip&#8230;</a></strong></p>
<img src="http://feeds.feedburner.com/~r/Catswhocode/~4/bEaofz6HL7Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.catswhocode.com/blog/10-super-useful-php-snippets-you-probably-havent-seen/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Tutorials and snippets to get started with CoffeeScript</title>
		<link>http://www.catswhocode.com/blog/tutorials-and-snippets-to-get-started-with-coffeescript</link>
		<comments>http://www.catswhocode.com/blog/tutorials-and-snippets-to-get-started-with-coffeescript#comments</comments>
		<pubDate>Mon, 09 Jan 2012 15:09:51 +0000</pubDate>
		<dc:creator>Jean-Baptiste Jung</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.catswhocode.com/blog/?p=4657</guid>
		<description><![CDATA[JavaScript is definitely an important part of a website as it allow the developer to interact directly with the web browser. Since 2005, lots of new JavaScript techniques and tools such as Ajax and jQuery became extremely popular and made the web a better place. Today, I'm introducing to you CoffeeScript, a new language that make JavaScript better and simpler.]]></description>
			<content:encoded><![CDATA[<h2>What is CoffeeScript?</h2>
<p>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&#8217;ll probably love CoffeeScript a lot. Instead of awkward braces and semicolons, JavaScript has always had a gorgeous object model at its heart.</p>
<p>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.</p>
<h2>Installing CoffeeScript</h2>
<p>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 <a href="http://nodejs.org/">Node.js</a> as well as <a href="http://npmjs.org/">npm</a>, the Node Package Manager. </p>
<p>Once done, you can install CoffeeScript by running the following command: </p>
<pre>npm install -g coffee-script</pre>
<p>CoffeeScript is now installed. Next step is to compile a <code>.coffee</code> file into a <code>.js</code> file. Use the following syntax to do so:</p>
<pre>coffee --compile example.coffee</pre>
<p><a href="http://coffeescript.org/">CoffeeScript.org</a> is the official website of the CoffeeScript language. Don&#8217;t hesitate to visit it, it&#8217;s full of helpful ressources. </p>
<h2>Tutorial: Basics of CoffeeScript</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2012/01/coffeescript-tutorial-1.png" alt="" /><br />
A great tutorial that demonstrate all you need to get started with CoffeeScript: installation, configuration and first lines of codes.<br />
<strong>&rarr; <a href="http://sixrevisions.com/javascript/coffeescript-basics/">View tutorial</a></strong></p>
<h2>Tutorial: Rocking out with CoffeeScript</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2012/01/coffeescript-tutorial-2.png" alt="" /><br />
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.<br />
<strong>&rarr; <a href="http://net.tutsplus.com/tutorials/javascript-ajax/rocking-out-with-coffeescript/">View tutorial</a></strong></p>
<h2>Tutorial: Creating an iOS-like Home Screen with CoffeeScript</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2012/01/coffeescript-tutorial-3.png" alt="" /><br />
Now, let&#8217;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.<br />
<strong>&rarr; <a href="http://tutorialzine.com/2011/10/ios-homescreen-coffeescript/">View tutorial</a></strong></p>
<h2>CoffeeScript snippet: Shorten url using Google&#8217;s Goo.gl service</h2>
<p>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&#8217;ll need your own Google API key for the code to work.</p>
<pre>
apikey = &quot;YOUR GOOGLE API KEY GOES HERE&quot;

shorten_url = (url, success_callback, error_callback) -&gt;

  xhr = Titanium.Network.createHTTPClient()
  xhr.open &quot;POST&quot;, &quot;https://www.googleapis.com/urlshortener/v1/url?key=&quot; + apikey
  xhr.setRequestHeader &quot;Content-type&quot;, &quot;application/json&quot;
  xhr.onload = () -&gt; success_callback xhr.status, xhr.responseText
  xhr.onerror = () -&gt; error_callback xhr.status, xhr.responseText
  content =  &quot;{\&quot;longUrl\&quot;: \&quot;#{url}\&quot;}&quot;
  xhr.send content
</pre>
<p><strong>&rarr; Source: <a href="http://developer.appcelerator.com/question/125880/coffeescript-snippet-for-accessing-googles-url-shortening-service-not-actually-a-question">http://developer.appcelerator.com/question/125880/&#8230;</a></strong></p>
<h2>CoffeScript snippet: Read in a file</h2>
<p>CoffeeScript make reading files very easy, as shown below:</p>
<pre>fs.readFile 'data.txt', (err, data) -> fileText = data</pre>
<p><strong>&rarr; Source: <a href="http://ricardo.cc/2011/06/02/10-CoffeeScript-One-Liners-to-Impress-Your-Friends.html">http://ricardo.cc/2011/06/02/10-CoffeeScript-One-Liners-to-Impress-Your-Friends.html</a></strong></p>
<h2>CoffeScript snippet: Fetch and Parse a XML web service</h2>
<p>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: </p>
<pre>request.get { uri:'path/to/api.json', json: true }, (err, r, body) -> results = body</pre>
<p><strong>&rarr; Source: <a href="http://ricardo.cc/2011/06/02/10-CoffeeScript-One-Liners-to-Impress-Your-Friends.html">http://ricardo.cc/2011/06/02/10-CoffeeScript-One-Liners-to-Impress-Your-Friends.html</a></strong></p>
<h2>CoffeeScript snippet: Finding substrings</h2>
<p>Another very common task, made easier with CoffeeScript:</p>
<pre>
message = "This is a test string. This has a repeat or two. This might even have a third."
message.indexOf "This", 0
</pre>
<p><strong>&rarr; Source: <a href="http://coffeescriptcookbook.com/chapters/strings/finding-substrings">http://coffeescriptcookbook.com/chapters/strings/finding-substrings</a></strong></p>
<img src="http://feeds.feedburner.com/~r/Catswhocode/~4/0NGFY9DojsQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.catswhocode.com/blog/tutorials-and-snippets-to-get-started-with-coffeescript/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>JavaScript frameworks, tools and techniques to create killer applications</title>
		<link>http://www.catswhocode.com/blog/javascript-frameworks-tools-and-techniques-to-create-killer-applications</link>
		<comments>http://www.catswhocode.com/blog/javascript-frameworks-tools-and-techniques-to-create-killer-applications#comments</comments>
		<pubDate>Mon, 02 Jan 2012 05:00:43 +0000</pubDate>
		<dc:creator>Jean-Baptiste Jung</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.catswhocode.com/blog/?p=4637</guid>
		<description><![CDATA[Web browsers are becoming more and more powerful, and JavaScript is definitely making the web an ever more interesting place. In this article, I have compiled the most interesting JavaScript frameworks, tools and techniques to create killer applications and websites.]]></description>
			<content:encoded><![CDATA[<h2>Ofmlabs Codecs: Pure JavaScript audio decoding</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/12/ofmlabs.png" alt=""/><br />
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.<br />
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.<br />
<strong>&rarr; Visit <a href="http://codecs.ofmlabs.org/">Ofmlabs Codecs</a></strong></p>
<h2>Popcorn.js</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/12/popcorn.png" alt=""/><br />
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.<br />
<strong>&rarr; Visit <a href="http://mozillapopcorn.org/popcornjs/">Popcorn.js</a></strong></p>
<h2>JSZip: Create .zip files with JavaScript</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/12/jszip.png" alt=""/><br />
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.</p>
<p>Is it simple and easy, you ask? Yes, definitely. Look at the example code below:</p>
<pre>
zip = new JSZip();
zip.add("Hello.", "hello.txt");
Downloadify.create('downloadify',{
...
  data: function(){
    return zip.generate();
  },
...
  dataType: 'base64'
});
</pre>
<p><strong>&rarr; Visit <a href="http://jszip.stuartk.co.uk/">JSZip</a></strong></p>
<h2>Money.js: JavaScript currency converter</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/12/moneyjs.png" alt=""/><br />
Currency conversion is a recurrent task in many businessses, but it&#8217;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!<br />
<strong>&rarr; Visit <a href="http://josscrowcroft.github.com/money.js/">Money.js</a></strong></p>
<h2>Resizable videos with fitvids.js</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/12/fitvids.png" alt=""/><br />
Last year, <a href="http://www.catswhocode.com/blog/awesome-tutorials-to-master-responsive-web-design">responsible web design</a> 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.<br />
<strong>&rarr; Visit <a href="http://fitvidsjs.com/">fitvids.js</a></strong></p>
<h2>Generate pdf files with pdfkit for node.js</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2012/01/pdfkit.png" alt=""/><br />
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!<br />
<strong>&rarr; Visit <a href="http://pdfkit.org/">pdfkit</a></strong></p>
<h2>Impress.js: </h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2012/01/impress.png" alt=""/><br />
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?<br />
<strong>&rarr; Visit <a href="http://bartaz.github.com/impress.js/">impress.js</a></strong></p>
<img src="http://feeds.feedburner.com/~r/Catswhocode/~4/AL5TmJ_-QA0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.catswhocode.com/blog/javascript-frameworks-tools-and-techniques-to-create-killer-applications/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Super useful WordPress hacks and snippets</title>
		<link>http://www.catswhocode.com/blog/super-useful-wordpress-hacks-and-snippets</link>
		<comments>http://www.catswhocode.com/blog/super-useful-wordpress-hacks-and-snippets#comments</comments>
		<pubDate>Mon, 19 Dec 2011 16:11:52 +0000</pubDate>
		<dc:creator>Jean-Baptiste Jung</dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://www.catswhocode.com/blog/?p=4625</guid>
		<description><![CDATA[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!]]></description>
			<content:encoded><![CDATA[<h2>Add Google+ button to your posts automatically</h2>
<p>Google+ is a new &#8220;social&#8221; service offered by Internet giant Google. If you want to let your visitor &#8220;plus&#8221; your post, why not adding a Google+ button to all of your entries automatically? </p>
<p>Simply paste the code below into your <code>functions.php</code> file. Once you saved the file, the Google+ button will be automatically displayed near your posts. </p>
<pre>
add_filter(&#39;the_content&#39;, &#39;wpr_google_plusone&#39;);
function wpr_google_plusone($content) {
	$content = $content.&#39;&lt;div class=&quot;plusone&quot;&gt;&lt;g:plusone size=&quot;tall&quot; href=&quot;&#39;.get_permalink().&#39;&quot;&gt;&lt;/g:plusone&gt;&lt;/div&gt;&#39;;
	return $content;
}
add_action (&#39;wp_enqueue_scripts&#39;,&#39;wpr_google_plusone_script&#39;);
function wpr_google_plusone_script() {
	wp_enqueue_script(&#39;google-plusone&#39;, &#39;https://apis.google.com/js/plusone.js&#39;, array(), null);
}
</pre>
<p><strong>Source: <a href="http://www.wprecipes.com/wordpress-hook-automatically-add-a-google-button-to-your-posts">http://www.wprecipes.com/wordpress-hook-automatically-add-a-google-button-to-your-posts</a></strong></p>
<h2>Redirect RSS feeds to Feedburner</h2>
<p>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.</p>
<p>Edit line 4 and replace my feed url by yours. Once done, paste the code in your <code>functions.php</code> file. Save the file, and you&#8217;re done!</p>
<pre>
add_action('template_redirect', 'cwc_rss_redirect');
function cwc_rss_redirect() {
	if ( is_feed() &#038;&#038; !preg_match('/feedburner|feedvalidator/i', $_SERVER['HTTP_USER_AGENT'])){
		header('Location: http://feeds.feedburner.com/catswhocode');
		header('HTTP/1.1 302 Temporary Redirect');
	}
}
</pre>
<p><strong>Source: <a href="http://wp.smashingmagazine.com/2011/12/07/10-tips-optimize-wordpress-theme/">http://wp.smashingmagazine.com/2011/12/07/10-tips-optimize-wordpress-theme/</a></strong></p>
<h2>Track post views without using a plugin</h2>
<p>Are you curious about how many people are reading your posts? A few &#8220;view counts&#8221; plugins exists, but here&#8217;s a simple way to do this yourself. The first thing to do is to create the functions. Paste the code below into your <code>functions.php</code> file. </p>
<pre>
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 &quot;0 View&quot;;
    }
    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);
    }
}
</pre>
<p>Then, paste the code below within the <code>single.php</code> within the loop:</p>
<pre>&lt;?php setPostViews(get_the_ID()); ?&gt;</pre>
<p>Finally, paste the snippet below anywhere within the template where you would like to display the number of views:</p>
<pre>&lt;?php echo getPostViews(get_the_ID()); ?&gt;</pre>
<p>Source: <a href="http://wpsnipp.com/index.php/functions-php/track-post-views-without-a-plugin-using-post-meta/">http://wpsnipp.com/index.php/functions-php/track-post-views-without-a-plugin-using-post-meta/</a></strong></p>
<h2>Display number of Facebook fans in full text</h2>
<p>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&#8217;d like the count to be displayed.</p>
<pre>
&lt;?php
	$page_id = &quot;YOUR PAGE-ID&quot;;
	$xml = @simplexml_load_file(&quot;http://api.facebook.com/restserver.php?method=facebook.fql.query&amp;query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=&quot;.$page_id.&quot;&quot;) or die (&quot;a lot&quot;);
	$fans = $xml-&gt;page-&gt;fan_count;
	echo $fans;
?&gt;
</pre>
<p><strong>Source: <a href="http://wp-snippets.com/742/display-number-facebook-fans/">http://wp-snippets.com/742/display-number-facebook-fans/</a></strong></p>
<h2>Display search terms from Google</h2>
<p>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&#8217;d like to display the search terms.</p>
<pre>
&lt;?php
$refer = $_SERVER[&quot;HTTP_REFERER&quot;];
if (strpos($refer, &quot;google&quot;)) {
	$refer_string = parse_url($refer, PHP_URL_QUERY);
	parse_str($refer_string, $vars);
	$search_terms = $vars[&#39;q&#39;];
	echo &#39;Welcome Google visitor! You searched for the following terms to get here: &#39;;
	echo $search_terms;
};
?&gt;
</pre>
<p>Of course, this snippet can also be used in order to log what user searched before arriving to your website.</p>
<p><strong>Source: <a href="http://wp-snippets.com/820/display-search-terms-from-google-users/">http://wp-snippets.com/820/display-search-terms-from-google-users/</a></strong></p>
<h2>Easily display external files using a shortcode</h2>
<p>When blogging, you may sometimes need to include a file from a remote website. The following code will create a shortcode so you&#8217;ll be able to include any file you want from your WordPress post editor.</p>
<p>The first step is to open your <code>functions.php</code> file and paste the code below in it.</p>
<pre>
function show_file_func( $atts ) {
  extract( shortcode_atts( array(
    &#39;file&#39; =&gt; &#39;&#39;
  ), $atts ) );

  if ($file!=&#39;&#39;)
    return @file_get_contents($file);
}

add_shortcode( &#39;show_file&#39;, &#39;show_file_func&#39; );
</pre>
<p>Once you saved your <code>functions.php</code> file, you can use the shortcode using the following syntax:</p>
<pre>[show_file file="http://www.somesite.com/somepage.html"]
</pre>
<p><strong>Source: <a href="http://www.prelovac.com/vladimir/wordpress-shortcode-snippet-to-display-external-files">http://www.prelovac.com/vladimir/wordpress-shortcode-snippet-to-display-external-files</a></strong></p>
<h2>Email contributors when their posts are published</h2>
<p>In case you&#8217;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 <code>functions.php</code>. Once done, an automated email will be sent to any contributors when his posts are published.</p>
<pre>
function wpr_authorNotification($post_id) {
   $post = get_post($post_id);
   $author = get_userdata($post-&gt;post_author);

   $message = &quot;
      Hi &quot;.$author-&gt;display_name.&quot;,
      Your post, &quot;.$post-&gt;post_title.&quot; has just been published. Well done!
   &quot;;
   wp_mail($author-&gt;user_email, &quot;Your article is online&quot;, $message);
}
add_action(&#39;publish_post&#39;, &#39;wpr_authorNotification&#39;);
</pre>
<p><strong>Source: <a href="http://www.wprecipes.com/how-to-automatically-email-contributors-when-their-posts-are-published">http://www.wprecipes.com/how-to-automatically-email&#8230;</a></strong></p>
<h2>Display snapshots of external websites using a shortcode</h2>
<p>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.</p>
<p>Let&#8217;s start by adding the functions below into your <code>functions.php</code> file.</p>
<pre>
&lt;?php
function bm_sc_mshot ($attributes, $content = &#39;&#39;, $code = &#39;&#39;) {

	extract(shortcode_atts(array(
		&#39;url&#39; =&gt; &#39;&#39;,
		&#39;width&#39; =&gt; 250,
	), $attributes));

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

	if ($imageUrl == &#39;&#39;) {
		return &#39;&#39;;
	} else {
		$image = &#39;&lt;img src=&quot;&#39; . $imageUrl . &#39;&quot; alt=&quot;&#39; . $url . &#39;&quot; width=&quot;&#39; . $width . &#39;&quot;/&gt;&#39;;
		return &#39;&lt;div class=&quot;browsershot mshot&quot;&gt;&lt;a href=&quot;&#39; . $url . &#39;&quot;&gt;&#39; . $image . &#39;&lt;/a&gt;&lt;/div&gt;&#39;;
	}

}

function bm_mshot ($url = &#39;&#39;, $width = 250) {

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

}

add_shortcode(&#39;browsershot&#39;, &#39;bm_sc_mshot&#39;);
?&gt;
</pre>
<p>Once done, you can use the <code>[browsershot]</code> shortcode on WordPress editor, as shown below:</p>
<pre>[browsershot url="http://link-to-website" width="foo-value"]</pre>
<p><strong>Source: <a href="http://www.binarymoon.co.uk/2010/02/automated-take-screenshots-website-free/">http://www.binarymoon.co.uk/2010/02/automated-take-screenshots-website-free/</a></strong></p>
<h2>List sites from your network</h2>
<p>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&#8217;s actually pretty easy using the following function.</p>
<p>The first step is, as you can guess, to add the required functions into your theme <code>functions.php</code> file.</p>
<pre>
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&#39;ll use
   // $wpdb to roll out our own SQL query instead. Because the query can be
   // memory-intensive, we&#39;ll store the results using the Transients API
   if ( false === ( $site_list = get_transient( &#39;multisite_site_list&#39; ) ) ) {
      global $wpdb;
      $site_list = $wpdb-&gt;get_results( $wpdb-&gt;prepare(&#39;SELECT * FROM wp_blogs ORDER BY blog_id&#39;) );
      // Set the Transient cache to expire every two hours
      set_site_transient( &#39;multisite_site_list&#39;, $site_list, $expires );
   }

   $current_site_url = get_site_url( get_current_blog_id() );

   $html = &#39;
&lt;ul id=&quot;network-menu&quot;&gt;&#39; . &quot;\n&quot;;

   foreach ( $site_list as $site ) {
      switch_to_blog( $site-&gt;blog_id );
      $class = ( home_url() == $current_site_url ) ? &#39; class=&quot;current-site-item&quot;&#39; : &#39;&#39;;
      $html .= &quot;\t&quot; . &#39;
&lt;li id=&quot;site-&#39; . $site-&gt;blog_id . &#39;&quot; &#39;=&quot;&quot; .=&quot;&quot; $class=&quot;&quot;&gt;&lt;a href=&quot;&#39; . home_url() . &#39;&quot;&gt;&#39; . get_bloginfo(&#39;name&#39;) . &#39;&lt;/a&gt;&lt;/li&gt;

&#39; . &quot;\n&quot;;
      restore_current_blog();
   }

   $html .= &#39;&lt;/ul&gt;

&lt;!--// end #network-menu --&gt;&#39; . &quot;\n\n&quot;;

   return $html;
}
</pre>
<p>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.</p>
<pre>
&lt;?php
// Multisite Network Menu
$network_menu = wp_list_sites();
if( $network_menu ):
?&gt;
&lt;div id=&quot;network-menu&quot;&gt;
   &lt;?php echo $network_menu; ?&gt;
&lt;/div&gt;

&lt;!--// end #network-menu --&gt;
&lt;?php endif; ?&gt;
</pre>
<p><strong>Source: <a href="http://wp.smashingmagazine.com/2011/11/17/wordpress-multisite-practical-functions-methods/">http://wp.smashingmagazine.com/2011/11/17/wordpress-multisite-practical-functions-methods/</a></strong></p>
<h2>Add post class if the post has a thumbnail</h2>
<p>When styling your theme, it can be tricky to deal with post that have a post thumbnail and those who don&#8217;t. In order to simplify yor front-end coding, you should use this code, who add a <code>has_thumb</code> css class to the post class.</p>
<p>Just paste the code below into your <code>functions.php</code> file. </p>
<pre>
function has_thumb_class($classes) {
	global $post;
	if( has_post_thumbnail($post-&gt;ID) ) { $classes[] = &#39;has_thumb&#39;; }

		return $classes;
}
add_filter(&#39;post_class&#39;, &#39;has_thumb_class&#39;);
</pre>
<p><strong>Source: <a href="http://wp-snippets.com/2178/add-post-class-if-post-has-thumbnail/">http://wp-snippets.com/2178/add-post-class-if-post-has-thumbnail/</a></strong></p>
<img src="http://feeds.feedburner.com/~r/Catswhocode/~4/QUhT_Aw4-wI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.catswhocode.com/blog/super-useful-wordpress-hacks-and-snippets/feed</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>10 awesome jQuery snippets</title>
		<link>http://www.catswhocode.com/blog/10-awesome-jquery-snippets</link>
		<comments>http://www.catswhocode.com/blog/10-awesome-jquery-snippets#comments</comments>
		<pubDate>Mon, 21 Nov 2011 15:10:42 +0000</pubDate>
		<dc:creator>Jean-Baptiste Jung</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.catswhocode.com/blog/?p=4615</guid>
		<description><![CDATA[jQuery gave a new life to JavaScript coding. Thanks to this great tool, it is now possible to build powerful and responsive web pages. In this article, I have compiled 10 jQuery snippets that will definitely help you in your daily client-side coding.]]></description>
			<content:encoded><![CDATA[<h2>Preloading images</h2>
<p>Preloading images is useful: Instead of loading an image when the user request it, we preload them in the background so they are ready to be displayed. Doing so in jQuery is very simple, as shown below:</p>
<pre>
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement(&#39;img&#39;);
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }

jQuery.preLoadImages("image1.gif", "/path/to/image2.png");
</pre>
<p><strong>&rarr; Source: <a href="http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript">http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript</a></strong></p>
<h2>target=&#8221;blank&#8221; links</h2>
<p>The following snippet will open all links with the <code>rel="external"</code> attribute in a new tab/window. The code can be easily customized to only open links with a specific class.</p>
<pre>
$('a[@rel$='external']').click(function(){
     this.target = "_blank";
});

/*
   Usage:
   &lt;a href="http://www.catswhocode.com" rel="external"&gt;catswhocode.com&lt;/a&gt;
*/
</pre>
<p><strong>&rarr; Source: <a href="http://snipplr.com/view/315/-jquery--target-blank-links/">http://snipplr.com/view/315/-jquery&#8211;target-blank-links/</a></strong></p>
<h2>Add a class to the &lt;body&gt; tag if JavaScript is enabled</h2>
<p>This snippet is just a line of code, but it is one of the easiest way to detect if JavaScript is enabled on the client browser. If yes, a <code>hasJS</code> class will be added to the <code>&lt;body&gt;</code> tag.</p>
<pre>
$('body').addClass('hasJS');
</pre>
<p><strong>&rarr; Source: <a href="http://eisabainyo.net/weblog/2010/09/01/10-useful-jquery-snippets/">http://eisabainyo.net/weblog/2010/09/01/10-useful-jquery-snippets/</a></strong></p>
<h2>Smooth scrolling to an anchor</h2>
<p>jQuery is known for its ability to let developers easily create stunning visual effects. A simple, but nice effect is smooth sliding to an anchor. The following snippet will create a smooth sliding effect when a link with the <code>topLink</code> class is clicked.</p>
<pre>
$(document).ready(function() {
	$(&quot;a.topLink&quot;).click(function() {
		$(&quot;html, body&quot;).animate({
			scrollTop: $($(this).attr(&quot;href&quot;)).offset().top + &quot;px&quot;
		}, {
			duration: 500,
			easing: &quot;swing&quot;
		});
		return false;
	});
});
</pre>
<p><strong>&rarr; Source: <a href="http://snipplr.com/view.php?codeview&#038;id=26739">http://snipplr.com/view.php?codeview&#038;id=26739</a></strong></p>
<h2>Fade in/out on hover</h2>
<p>Another very cool effect &#8211; which is very popular among clients &#8211; is indeed the fade in/fade out on mouseover. The code below set opacity to 100% on hover, and to 60% on mouseout.</p>
<pre>
$(document).ready(function(){
    $(&quot;.thumbs img&quot;).fadeTo(&quot;slow&quot;, 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads

    $(&quot;.thumbs img&quot;).hover(function(){
        $(this).fadeTo(&quot;slow&quot;, 1.0); // This should set the opacity to 100% on hover
    },function(){
        $(this).fadeTo(&quot;slow&quot;, 0.6); // This should set the opacity back to 60% on mouseout
    });
});
</pre>
<p><strong>&rarr; Source: <a href="http://snipplr.com/view/18606/">http://snipplr.com/view/18606/</a></strong></p>
<h2>Equal column height</h2>
<p>When building a column based website, you often want that all columns have the same height, as displayed in a good old table. This snippet calculate the height of the higher column and automatically adjust all other columns to this height.</p>
<pre>
var max_height = 0;
$(&quot;div.col&quot;).each(function(){
    if ($(this).height() &gt; max_height) { max_height = $(this).height(); }
});
$(&quot;div.col&quot;).height(max_height);
</pre>
<p><strong>&rarr; Source: <a href="http://web.enavu.com/tutorials/top-10-jquery-snippets-including-jquery-1-4/">http://web.enavu.com/tutorials/top-10-jquery-snippets-including-jquery-1-4/</a></strong></p>
<h2>Enable HTML5 markup on older browsers</h2>
<p>HTML5 is definitely the future of client-side web development. Unfortunely, some old browsers do not even recognize new tags such as <code>header</code> or <code>section</code>. This code will force old browsers to recognize the new tags introduced by HTML5.</p>
<pre>
(function(){if(!/*@cc_on!@*/0)return;var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(','),i=e.length;while(i--){document.createElement(e[i])}})()
</pre>
<p>A better solution is to link the .js file to the <code>&lt;head&gt;</code> part of your HTML page:</p>
<pre>
&lt;!--[if lt IE 9]&gt;
&lt;script src=&quot;http://html5shim.googlecode.com/svn/trunk/html5.js&quot;&gt;&lt;/script&gt;
&lt;![endif]--&gt;
</pre>
<p><strong>&rarr; Source: <a href="http://remysharp.com/2009/01/07/html5-enabling-script/">http://remysharp.com/2009/01/07/html5-enabling-script/</a></strong></p>
<h2>Test if the browser supports a specific CSS3 property</h2>
<p>Here is a simple jQuery function to check if the client browser supports a specific CSS3 property. In this example, <code>border-radius</code> is the property we want to check, but of course this can be modified easily.</p>
<p>Note that when passing the property, you have to omit the dash to prevent syntax error. So instead of <code>border-radius</code>, you have to pass &#8220;borderRadius&#8221; or &#8220;BorderRadius&#8221;.</p>
<pre>
var supports = (function() {
   var div = document.createElement(&#39;div&#39;),
      vendors = &#39;Khtml Ms O Moz Webkit&#39;.split(&#39; &#39;),
      len = vendors.length;

   return function(prop) {
      if ( prop in div.style ) return true;

      prop = prop.replace(/^[a-z]/, function(val) {
         return val.toUpperCase();
      });

      while(len--) {
         if ( vendors[len] + prop in div.style ) {
            // browser supports box-shadow. Do what you need.
            // Or use a bang (!) to test if the browser doesn&#39;t.
            return true;
         }
      }
      return false;
   };
})();

if ( supports(&#39;textShadow&#39;) ) {
   document.documentElement.className += &#39; textShadow&#39;;
</pre>
<p><strong>&rarr; Source: <a href="http://snipplr.com/view/44079">http://snipplr.com/view/44079</a></strong></p>
<h2>Get url parameters</h2>
<p>Getting url parameters is pretty easy using jQuery. The following snippet will do the job!</p>
<pre>
$.urlParam = function(name){
	var results = new RegExp(&#39;[\\?&amp;]&#39; + name + &#39;=([^&amp;#]*)&#39;).exec(window.location.href);
	if (!results) { return 0; }
	return results[1] || 0;
}
</pre>
<p><strong>&rarr; Source: <a href="http://snipplr.com/view/26662">http://snipplr.com/view/26662</a></strong></p>
<h2>Disable the &#8220;Enter&#8221; key in forms</h2>
<p>By default, a form can be submitted by pressing the &#8220;Enter&#8221; key. Thought, on some form, this keyboard shortcut can cause problems. Here is how you can prevent unwanted form submission by disabling the &#8220;Enter&#8221; key with jQuery.</p>
<pre>
$(&quot;#form&quot;).keypress(function(e) {
  if (e.which == 13) {
    return false;
  }
});
</pre>
<p><strong>&rarr; Source: <a href="http://snipplr.com/view/10943/disable-enter-via-jquery/">http://snipplr.com/view/10943/disable-enter-via-jquery/</a></strong></p>
<img src="http://feeds.feedburner.com/~r/Catswhocode/~4/uGYOdnpOWs8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.catswhocode.com/blog/10-awesome-jquery-snippets/feed</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>10+ .htaccess snippets to optimize your website</title>
		<link>http://www.catswhocode.com/blog/10-htaccess-snippets-to-optimize-your-website</link>
		<comments>http://www.catswhocode.com/blog/10-htaccess-snippets-to-optimize-your-website#comments</comments>
		<pubDate>Mon, 24 Oct 2011 14:21:18 +0000</pubDate>
		<dc:creator>Jean-Baptiste Jung</dc:creator>
				<category><![CDATA[Web development]]></category>

		<guid isPermaLink="false">http://www.catswhocode.com/blog/?p=4603</guid>
		<description><![CDATA[Apache .htaccess file is at the heart of your web server and control how your website will react to different actions performed by your visitors. I've compiled 10+ awesome .htaccess snippets to optimize your website in many ways: Redirections, performances, ease of use... Enjoy!]]></description>
			<content:encoded><![CDATA[<p>All of the snippets below have to be pasted into your <code>.htaccess</code> file, which is located on the root of your Apache server.<br />
<strong>Waring: Always make sure you have a working backup before editing your .htaccess file!</strong></p>
<h2>Force trailing slash</h2>
<p>Many clients of mine asked me for always having a trailing slash at the end of their urls. Looks like it&#8217;s great for SEO. The following snippet will alwyas add a trailing slash to your site urls.</p>
<pre>
&lt;IfModule mod_rewrite.c&gt;
 RewriteCond %{REQUEST_URI} /+[^\.]+$
 RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
&lt;/IfModule&gt;
</pre>
<p><strong>Source: <a href="http://perishablepress.com/code-snippets/">http://perishablepress.com/code-snippets/</a></strong></p>
<h2>Prevent hotlinking</h2>
<p>Hotlinking (the act of using images from another site than yours) is unfortunely a common practice which can waste lots of your precious bandwidth. This useful snippets will redirect all hotlinked images to a specific image, defined on line 6.</p>
<pre>
RewriteEngine On
#Replace ?mysite\.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mysite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your &quot;don&#39;t hotlink&quot; image url
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]
</pre>
<p><strong>Source: <a href="http://www.wprecipes.com/how-to-protect-your-wordpress-blog-from-hotlinking">http://www.wprecipes.com/how-to-protect-your&#8230;</a></strong></p>
<h2>Redirect mobile devices</h2>
<p>If your site is not using <a href="http://www.catswhocode.com/blog/awesome-tutorials-to-master-responsive-web-design">responsive web design</a> yet, it could be very useful to be able to redirect mobile device to a mobile-specific version of your website.</p>
<pre>
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/m/.*$
RewriteCond %{HTTP_ACCEPT} &quot;text/vnd.wap.wml|application/vnd.wap.xhtml+xml&quot; [NC,OR]
RewriteCond %{HTTP_USER_AGENT} &quot;acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-&quot; [NC,OR]
RewriteCond %{HTTP_USER_AGENT} &quot;dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-&quot; [NC,OR]
RewriteCond %{HTTP_USER_AGENT}  &quot;maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv&quot; [NC,OR]
RewriteCond %{HTTP_USER_AGENT} &quot;palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany&quot; [NC,OR]
RewriteCond %{HTTP_USER_AGENT} &quot;sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo&quot; [NC,OR]
RewriteCond %{HTTP_USER_AGENT} &quot;teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi&quot; [NC,OR]
RewriteCond %{HTTP_USER_AGENT} &quot;wapp|wapr|webc|winw|winw|xda|xda-&quot; [NC,OR]
RewriteCond %{HTTP_USER_AGENT} &quot;up.browser|up.link|windowssce|iemobile|mini|mmp&quot; [NC,OR]
RewriteCond %{HTTP_USER_AGENT} &quot;symbian|midp|wap|phone|pocket|mobile|pda|psp&quot; [NC]
#------------- The line below excludes the iPad
RewriteCond %{HTTP_USER_AGENT} !^.*iPad.*$
#-------------
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC] #*SEE NOTE BELOW
RewriteRule ^(.*)$ /m/ [L,R=302]
</pre>
<p><strong>Source: <a href="http://snipplr.com/view.php?codeview&#038;id=55114">http://snipplr.com/view.php?codeview&#038;id=55114</a></strong></p>
<h2>Force download of a specific filetype</h2>
<p>For some reasons you may need to force download of specific files, such as MP3s or XLS. This code snippets will prevent your visitor&#8217;s browser to read the file and force downloading instead.</p>
<pre>
&lt;Files *.xls&gt;
  ForceType application/octet-stream
  Header set Content-Disposition attachment
&lt;/Files&gt;
&lt;Files *.eps&gt;
  ForceType application/octet-stream
  Header set Content-Disposition attachment
&lt;/Files&gt;
</pre>
<p><strong>Source: <a href="http://snipplr.com/view.php?codeview&#038;id=54752">http://snipplr.com/view.php?codeview&#038;id=54752</a></strong></p>
<h2>Cross Domain Font embedding for Firefox</h2>
<p>When embedding a font, Firefox do not allow you to embed from an external website. Using the <code>.htaccess</code> snippet below, you can bypass this limitation.</p>
<pre>
&lt;FilesMatch &quot;\.(ttf|otf|eot|woff)$&quot;&gt;
&lt;IfModule mod_headers.c&gt;
    Header set Access-Control-Allow-Origin &quot;http://yourdomain.com&quot;
&lt;/IfModule&gt;
&lt;/FilesMatch&gt;
</pre>
<p><strong>Source: <a href="http://snipplr.com/view/53703">http://snipplr.com/view/53703</a></strong></p>
<h2>Speed up your site with .htaccess caching</h2>
<p>This is probably the most useful snippet of this whole list. By using some simple .htaccess file cahing, you can dramatically increase your website speed. A snippet you should always have on your toolbox!</p>
<pre>
# 1 YEAR
&lt;FilesMatch &quot;\.(ico|pdf|flv)$&quot;&gt;
Header set Cache-Control &quot;max-age=29030400, public&quot;
&lt;/FilesMatch&gt;
# 1 WEEK
&lt;FilesMatch &quot;\.(jpg|jpeg|png|gif|swf)$&quot;&gt;
Header set Cache-Control &quot;max-age=604800, public&quot;
&lt;/FilesMatch&gt;
# 2 DAYS
&lt;FilesMatch &quot;\.(xml|txt|css|js)$&quot;&gt;
Header set Cache-Control &quot;max-age=172800, proxy-revalidate&quot;
&lt;/FilesMatch&gt;
# 1 MIN
&lt;FilesMatch &quot;\.(html|htm|php)$&quot;&gt;
Header set Cache-Control &quot;max-age=60, private, proxy-revalidate&quot;
&lt;/FilesMatch&gt;
</pre>
<p><strong>Source: <a href="http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html">http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html</a></strong></p>
<h2>Stop spam on your WordPress blog</h2>
<p>Sick of spammers on your WordPress blog? Of course, Akismet helps a lot, but your <code>.htaccess</code> file can also help: Today’s recipe is a snippet that prevent spam bots to directly access your <code>wp-comments-post.php</code> file, which is used to post comments on your blog.</p>
<pre>
&lt;IfModule mod_rewrite.c&gt;
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*yourdomainname.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]
&lt;/IfModule&gt;
</pre>
<p><strong>Source: <a href="http://www.wprecipes.com/reduce-spam-on-your-wordpress-blog-by-using-htaccess">http://www.wprecipes.com/reduce-spam-on-your-wordpress-blog-by-using-htaccess</a></strong></p>
<h2>Redirect different feeds to a single format</h2>
<p>Years ago, differents feed formats, such as RSS, Atom or Rdf were used. Nowadays, it seems that RSS is definitely the most used. This snippets allows you to redirect all feeds formats to a single feed. This snippet can be used &#8220;as it&#8221; on WordPress blogs.</p>
<pre>
&lt;IfModule mod_alias.c&gt;
 RedirectMatch 301 /feed/(atom|rdf|rss|rss2)/?$ http://example.com/feed/
 RedirectMatch 301 /comments/feed/(atom|rdf|rss|rss2)/?$ http://example.com/comments/feed/
&lt;/IfModule&gt;
</pre>
<p><strong>Source: <a href="http://www.wprecipes.com/redirect-feeds-to-a-single-format">http://www.wprecipes.com/redirect-feeds-to-a-single-format</a></strong></p>
<h2>Configure your website for HTML5 videos</h2>
<p>HTML5 is bringing lots of new exiting options in the world of web development. Among other cool features, being able to play videos without using Flash is really cool. Though, you have to configure your server properly to work with the latest HTML5 video standards. This snippet will definitely help. </p>
<pre>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
AddType video/ogg .ogv
AddType video/ogg .ogg
AddType video/mp4 .mp4
AddType video/webm .webm
AddType application/x-shockwave-flash swf
</pre>
<p><strong>Source: <a href="http://snipplr.com/view.php?codeview&#038;id=53437">http://snipplr.com/view.php?codeview&#038;id=53437</a></strong></p>
<h2>Log PHP errors</h2>
<p>Instead of displaying PHP errors to your site (and to possible hackers&#8230;) this code snippet will log it into a <code>.log</code> file while hiding errors to visitors.</p>
<pre>
# display no errs to user
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
# log to file
php_flag log_errors on
php_value error_log /location/to/php_error.log
</pre>
<p><strong>Source: <a href="http://css-tricks.com/snippets/htaccess/php-error-logging/">http://css-tricks.com/snippets/htaccess/php-error-logging/</a></strong></p>
<h2>Run PHP inside JavaScript files</h2>
<p>When coding in JavaScript, it can very useful to be able to use PHP inside the .js files, for example for retrieving data from your database. Here is a snippet to allow the use of PHP inside .js files.</p>
<pre>
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js

&lt;FilesMatch &quot;\.(js|php)$&quot;&gt;
SetHandler application/x-httpd-php
&lt;/FilesMatch&gt;
</pre>
<p><strong>Source: <a href="http://www.kavoir.com/2010/07/how-to-execute-run-php-code-inside-javascript-files.html">http://www.kavoir.com/2010/07/how-to-execute-run-php-code-inside-javascript-files.html</a></strong></p>
<img src="http://feeds.feedburner.com/~r/Catswhocode/~4/qgUS-HKGFuY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.catswhocode.com/blog/10-htaccess-snippets-to-optimize-your-website/feed</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Awesome tutorials to master responsive web design</title>
		<link>http://www.catswhocode.com/blog/awesome-tutorials-to-master-responsive-web-design</link>
		<comments>http://www.catswhocode.com/blog/awesome-tutorials-to-master-responsive-web-design#comments</comments>
		<pubDate>Mon, 10 Oct 2011 14:46:56 +0000</pubDate>
		<dc:creator>Jean-Baptiste Jung</dc:creator>
				<category><![CDATA[CSS]]></category>

		<guid isPermaLink="false">http://www.catswhocode.com/blog/?p=4583</guid>
		<description><![CDATA[In a few month, responsive web design has become a very important part of designing and developping a website. Due to the rise of mobile devices such as iPads, iPhones and other smart phones, your website must be easy to read and use in multiple resolution. In this post, I have compiled those awesome tutorials that will help you to master responsive web design.]]></description>
			<content:encoded><![CDATA[<h2>Create an adaptable website layout with CSS3 media queries</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/05/css3-media-queries.jpg" alt="" /><br />
With the rise of both very large screens and mobile devices, web developers have to be able to create websites that display correctly and look good whatever the device is. Sure, you can use good old techniques like fluid layouts, but I’ve got something better to show you today. This tutorial will teach you how you can create an adaptable website layout using CSS3.<br />
<strong>&rarr; Read tutorial: <a href="http://www.catswhocode.com/blog/create-an-adaptable-website-layout-with-css3-media-queries">Create an adaptable website layout with CSS3 media queries</a></strong></p>
<h2>Fluid images</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/10/fluid-images.png" alt="" /><br />
This tutorial will shown you how to make your image scales down when the browser is resized or when your website is viewed through a smaller screen.<br />
<strong>&rarr; Read tutorial: <a href="http://unstoppablerobotninja.com/entry/fluid-images/">Fluid images</a></strong></p>
<h2>Elastic videos</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/10/css-elastic-videos.png" alt="" /><br />
Nowadays, videos are widely used on the web. This useful tutorial written by Nick La (I&#8217;ve always be a fan of his work!) will show you how to make your videos scales down according to the window size.<br />
<strong>&rarr; Read tutorial: <a href="http://webdesignerwall.com/tutorials/css-elastic-videos">CSS3: Elastic videos</a></strong></p>
<h2>Optimizing your emails for mobile devices</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/10/email-mobile-devices.png" alt="" /><br />
As mobile devices are more and more used, more people are receiving their emails on their phones instead of their computer. For this reason, it is important that newsletter emails can be easily read on a small screen. This tutorial is going to show you how to create html emails than can adapt to mobile devices. A must read for everyone sending newsletters!<br />
<strong>&rarr; Read tutorial: <a href="http://www.campaignmonitor.com/blog/post/3163/optimizing-your-emails-for-mobile-devices-with-media/">Optimizing your emails for mobile devices with the @media query</a></strong></p>
<h2>Images that match text height</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/10/image-match-text.png" alt="" /><br />
This tutorial descibres a very clever way to fill up the entire available space with images. Images are scaled, they are spaced more or less according to the text height.<br />
<strong>&rarr; Read tutorial: <a href="http://zomigi.com/blog/css-effect-space-images-out-to-match-text-height/">CSS effect: space images out to match text height</a></strong></p>
<h2>Hiding and revealing portions of images</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/10/hiding-revealing-images.png" alt="" /><br />
Here is another great tutorial from zomigi.com. This useful article describes how to be able to reveal or hide portions of images depending of the screen size.<br />
<strong>&rarr; Read tutorial: <a href="http://zomigi.com/blog/hiding-and-revealing-portions-of-images/">Hiding and revealing portions of images</a></strong></p>
<h2>Responsive Data Tables</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/10/responsive-data-tables.png" alt="" /><br />
Wanna be able to create awesome tables that fits the display size? Chris Coyier from css-tricks.com have a very good post about the topic.<br />
<strong>&rarr; Read tutorial: <a href="http://css-tricks.com/9096-responsive-data-tables/">Responsive Data Tables</a></strong></p>
<h2>Context-Aware Image Sizing</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/10/responsive-images.png" alt="" /><br />
The technique described on this article is pretty interesting and consist in loading an image depending of the screen size. For example, if someone is viewing your website on an iPhone, he&#8217;ll see a low-resolution image, because it is useless to display 2000px wide images on small devices. On the other hand, people viewing your site on a computer will get a hi-resolution image.<br />
<strong>&rarr; Read tutorial: <a href="http://filamentgroup.com/lab/responsive_images_experimenting_with_context_aware_image_sizing/">Responsive Images: Experimenting with Context-Aware Image Sizing</a></strong></p>
<h2>Elastic text with Fittext.js</h2>
<p><img src="http://www.catswhocode.com/blog/wp-content/uploads/2011/06/fittext.png" alt="" /><br />
Well, this is more a tool than a tutorial, but Fittext is so useful than it totally deserve its place on this article. FitText is a small JavaScript tool  that allows the automatic resizing of a text regarding the size of its parent element. For a demo, just have a look to the website and resize your browser: The text will fit.<br />
<strong>&rarr; Read tutorial: <a href="http://fittextjs.com/">Fittext</a></strong></p>
<img src="http://feeds.feedburner.com/~r/Catswhocode/~4/Wc1fHH0lYio" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.catswhocode.com/blog/awesome-tutorials-to-master-responsive-web-design/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>7 new techniques every web developer should know</title>
		<link>http://www.catswhocode.com/blog/7-new-techniques-every-web-developer-should-know</link>
		<comments>http://www.catswhocode.com/blog/7-new-techniques-every-web-developer-should-know#comments</comments>
		<pubDate>Mon, 19 Sep 2011 14:04:15 +0000</pubDate>
		<dc:creator>Jean-Baptiste Jung</dc:creator>
				<category><![CDATA[Web development]]></category>

		<guid isPermaLink="false">http://www.catswhocode.com/blog/?p=4562</guid>
		<description><![CDATA[Web developers always have to update their knowledges and learn new technologies if they want to stay tuned with today's coding. Today, I'm going to show you 7 recent web development techniques that you should definitely learn, or improve if you already know them.]]></description>
			<content:encoded><![CDATA[<h2>CSS3 media queries</h2>
<p>With the rise of mobile devices, and on the other hand, of very wide displays, creating a website that looks great in both big and small devices is definitely a challenge for web designers and developers. Happily, the CSS3 specification have a new feature which allow web developers to define styles for a specific display size only.</p>
<p>For example, the code below show how to apply a specific style only if the client display is smaller than 767px.</p>
<pre>
@media screen and (max-width:767px){
	#container{
		width:320px;
	} 

	header h1#logo a{
		width:320px;
		height:44px;
		background:url(image-small.jpg) no-repeat 0 0;
	}                           

}
</pre>
<p><strong>More info: <a href="http://www.catswhocode.com/blog/create-an-adaptable-website-layout-with-css3-media-queries">Create an adaptable website layout with CSS3 media queries</a></strong></p>
<h2>Font resizing with REMs</h2>
<p>CSS3 introduces a few new units, including the rem unit, which stands for &#8220;root em&#8221;. If this hasn&#8217;t put you to sleep yet, then let&#8217;s look at how rem works.</p>
<p>The em unit is relative to the font-size of the parent, which causes the compounding issue. The rem unit is relative to the root—or the html—element. That means that we can define a single font size on the html element and define all rem units to be a percentage of that.</p>
<pre>
html { font-size: 62.5%; }
body { font-size: 1.4rem; } /* =14px */
h1   { font-size: 2.4rem; } /* =24px */
</pre>
<p><strong>More info: <a href="http://snook.ca/archives/html_and_css/font-size-with-rem">Font resizing with REMs</a></strong></p>
<h2>Cache pages for offline usage</h2>
<p>HTML5 introduces a great feature, offline caching. Basically, this feature allows you to tell the client browser to cache some pages so your visitor will be able to view it again, even if he&#8217;s not connected to the Internet.</p>
<p>Caching pages is pretty easy. The first thing to do is to add the following to your site <code>.htaccess</code> file:</p>
<pre>
AddType text/cache-manifest .manifest
</pre>
<p>Once done, you can create a file named, for example, <code>offline.manifest</code>, with the following directives: </p>
<pre>
CACHE MANIFEST

CACHE
index.html
style.css
image.jpg
</pre>
<p>And finally, link your <code>.manifest</code> file to your html document:</p>
<pre>
&lt;html manifest="/offline.manifest"&gt;
</pre>
<p>That&#8217;s all, and your page will now be cached if the client browser supports this technology.<br />
<strong>More info: <a href="http://www.catswhocode.com/blog/how-to-create-offline-html5-web-apps-in-5-easy-steps">How to create offline HTML5 web apps in 5 easy steps</a></strong></p>
<h2>Server-side JavaScript</h2>
<p>Since the mid-90&#8242;s, JavaScript has been a very popular client-side language for web developers. But nowadays, JavaScript is becoming more and more used  on the server side. Why? Because now we have powerful server-side JavaScript environments such as <a href="http://www.jaxer.org/">Jaxer</a>, <a href="http://nodejs.org/">Node.js</a> and <a href="http://narwhaljs.org/">Narwhal</a>.</p>
<p>The code belows demonstrate how to create a simple <em>Hello World</em> using Node.js.</p>
<pre>
var sys = require("sys");
sys.puts("Hello World!");
</pre>
<p><strong>More info: <a href="http://net.tutsplus.com/tutorials/javascript-ajax/learning-serverside-javascript-with-node-js/">Learning Server-Side JavaScript with Node.js</a></strong></p>
<h2>HTML5 drag &#038; drop</h2>
<p>Thanks to new technologies such as HTML5, the web is becoming more and more user-friendly. Now, it is possible to easily implement drag and drop on your web pages. This is very useful, for example for a shopping basket.</p>
<p>In order to make an element draggable, you simply have to add it the <code>draggable="true"</code> attribute, as shown in the example below:</p>
<pre>
&lt;div id=&quot;columns&quot;&gt;
  &lt;div class=&quot;column&quot; draggable=&quot;true&quot;&gt;&lt;header&gt;A&lt;/header&gt;&lt;/div&gt;
  &lt;div class=&quot;column&quot; draggable=&quot;true&quot;&gt;&lt;header&gt;B&lt;/header&gt;&lt;/div&gt;
  &lt;div class=&quot;column&quot; draggable=&quot;true&quot;&gt;&lt;header&gt;C&lt;/header&gt;&lt;/div&gt;
&lt;/div&gt;
</pre>
<p>Of course, after you made an element draggable, you have to use some JavaScript to control what it should do. I&#8217;m not going to explain how to do it (This may be a full article!) so you definitely have a look <a href="http://www.html5rocks.com/en/tutorials/dnd/basics/">there</a> if you&#8217;re interested in the topic.</p>
<p>Quick tip: If you want to prevent the text contents of draggable elements from being selectable, simply apply the following CSS rules:</p>
<pre>
[draggable] {
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}
</pre>
<p><strong>More info: <a href="http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/">Cross Browser HTML5 Drag and Drop</a></strong></p>
<h2>Forms, the HTML5 way</h2>
<p>The HTML5 specification introduces lots of new features regarding one of the most important element of a website: forms. For example, it is now possible to add date pickers, numeric spinners, as well as validating emails using regular expressions patterns.</p>
<p>The following code is pretty self-explanatory and shows most of the new forms-specific features introduced in the HTML5 specification.</p>
<pre>
&lt;form&gt;
	&lt;label for=&quot;range-slider&quot;&gt;Slider&lt;/label&gt;
	&lt;input type=&quot;range&quot; name=&quot;range-slider&quot; id=&quot;range-slider&quot; class=&quot;slider&quot; min=&quot;0&quot; max=&quot;20&quot; step=&quot;1&quot; value=&quot;0&quot;&gt;

	&lt;label for=&quot;numeric-spinner&quot;&gt;Numeric spinner&lt;/label&gt;
	&lt;input type=&quot;number&quot; name=&quot;numeric-spinner&quot; id=&quot;numeric-spinner&quot; value=&quot;2&quot;&gt;

	&lt;label for=&quot;date-picker&quot;&gt;Date picker&lt;/label&gt;
	&lt;input type=&quot;date&quot; name=&quot;date-picker&quot; id=&quot;date-picker&quot; value=&quot;2010-10-06&quot;&gt;

	&lt;label for=&quot;color-picker&quot;&gt;Color picker&lt;/label&gt;
	&lt;input type=&quot;color&quot; name=&quot;color-picker&quot; id=&quot;color-picker&quot; value=&quot;ff0000&quot;&gt;

	&lt;label for=&quot;text-field&quot;&gt;Text field with placeholder&lt;/label&gt;
	&lt;input type=&quot;text&quot; name=&quot;text-field&quot; id=&quot;text-field&quot; placeholder=&quot;Insert your text here&quot;&gt;

	&lt;label for=&quot;url-field&quot;&gt;Url field&lt;/label&gt;
	&lt;input type=&quot;url&quot; id=&quot;url-field&quot; name=&quot;url-field&quot; placeholder=&quot;http://net.tutsplus.com/&quot; required&gt;

	&lt;label for=&quot;email-field&quot;&gt;Email field&lt;/label&gt;
	&lt;input type=&quot;email&quot; id=&quot;email-field&quot; name=&quot;email-field&quot; placeholder=&quot;contact@ghinda.net&quot; required&gt;

	&lt;button type=&quot;submit&quot; class=&quot;ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only&quot; role=&quot;button&quot; aria-disabled=&quot;false&quot;&gt;
	&lt;span class=&quot;ui-button-text&quot;&gt;Submit form&lt;/span&gt;
	&lt;/button&gt;
&lt;/form&gt;
</pre>
<p><strong>More info: <a href="http://net.tutsplus.com/tutorials/html-css-techniques/how-to-build-cross-browser-html5-forms/">How to Build Cross-Browser HTML5 Forms</a></strong></p>
<h2>CSS animations</h2>
<p>Most modern browsers are now supporting CSS animations. Yes, CSS are now allowing you to create some simple animations, without the help of a client-side programming language such as JavaScript.</p>
<p>The following example shows how to make a background color change. As you can see, we have (for now) to use some proprietary properties such as <code>-moz-keyframes</code>. </p>
<pre>
#logo {
	margin: 15px 15px 0 15px;
	background: red;
	float: left;

	/* Firefox 4+ */
	-moz-animation-name: colour-change;
	-moz-animation-timing-function: linear;
	-moz-animation-iteration-count: infinite;
	-moz-animation-duration: 30s;

	/* Webkit */
	-webkit-animation-name: colour-change;
	-webkit-animation-timing-function: linear;
	-webkit-animation-iteration-count: infinite;
	-webkit-animation-duration: 30s;
}

@-moz-keyframes colour-change {
    0% {
		background: red;
    }
	33% {
		background: green;
    }
    66% {
    	background: blue;
    }
}

@-webkit-keyframes colour-change {
    0% {
		background: red;
    }
	33% {
		background: green;
    }
    66% {
    	background: blue;
    }
}
</pre>
<p><strong>More info: <a href="http://www.onextrapixel.com/2011/08/31/enhance-your-sites-with-css3-animations/">Enhance Your Sites with CSS3 Animations</a></strong></p>
<img src="http://feeds.feedburner.com/~r/Catswhocode/~4/Qx4tyNLqI6Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.catswhocode.com/blog/7-new-techniques-every-web-developer-should-know/feed</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Mastering HTML5 Prefetching</title>
		<link>http://www.catswhocode.com/blog/mastering-html5-prefetching</link>
		<comments>http://www.catswhocode.com/blog/mastering-html5-prefetching#comments</comments>
		<pubDate>Mon, 12 Sep 2011 14:19:58 +0000</pubDate>
		<dc:creator>Jean-Baptiste Jung</dc:creator>
				<category><![CDATA[HTML5]]></category>

		<guid isPermaLink="false">http://www.catswhocode.com/blog/?p=4546</guid>
		<description><![CDATA[Among other great features, HTML5 introduces prefetching, the art of loading pages before the user requested them. In this article, I'm going to discuss this new technique as well as showing you some ready to use examples to drastically improve your website loading time.]]></description>
			<content:encoded><![CDATA[<h2>What is prefetching, and why it is useful</h2>
<p>According to whatwg.org, <code>rel=prefetch</code> &quot;indicates that preemptively fetching and caching the specified resource is likely to be beneficial, as it is highly likely that the user will require this resource.&quot; Search engines sometimes add <code>&lt;link rel=prefetch href=&quot;URL of top search result&quot;&gt;</code> to the search results page if they feel that the top result is wildly more popular than any other.<br />
For example: using Firefox, search Google for CNN; view source; search for the keyword &quot;prefetch&quot;.</p>
<p>As loading time is a very important factor of a website quality, prefetching can definitely improve the user experience by loading pages <em>before</em> the user actually requested them. Of course, you have to be careful (Don&#8217;t prefetch your entire website!) but prefetching is definitely a feature that will make the web a better place.</p>
<h2>Prefetching pages with HTML5</h2>
<p>Prefetching pages is super easy to implement. The only thing you have to do is to place the following code with the <code>&lt;head&gt;</code> and <code>&lt;/head&gt;</code> tags of your page. The <code>href</code> attribute have to contain the url of the page to prefetch.</p>
<pre>&lt;link rel=&quot;prefetch&quot; href=&quot;http://www.example.com/&quot;&gt;</pre>
<p>It is also possible to prefetch only an image:</p>
<pre>&lt;link rel=&quot;prefetch&quot; href=&quot;http://www.catswhocode.com/wp-content/uploads/my_image.png&quot;&gt;</pre>
<h2>Browser support</h2>
<p>As prefetching (Or prerendering as Google Chrome name that feature) is a part of HTML5, it is currently not supported in all browsers:</p>
<ul>
<li><strong>Mozilla Firefox</strong>: Supported</li>
<li><strong>Google Chrome</strong>: Supported since version 13 (Use an alternate syntax)</li>
<li><strong>Safari</strong>: Currently not supported</li>
<li><strong>Internet Explorer</strong>: Currently not supported</li>
</ul>
<p>So, should you use it now? In my humble opinion, the answer is a definitive yes: Using prefetching now is possible in both Firefox and Chrome, and other browsers will probably implement it very soon. </p>
<p>Also, if you use prefetching on your website and the visitor browser do not support prefetching, nothing will happen. For what I&#8217;ve seen during some personal tests, it is safe to use prefetching as browsers will either implement it, or completely ignore it. </p>
<p>Another thing to note is that Google Chrome do not use the <code>prefetch</code> attribute and use <code>prerender</code> instead. This means that you have to implement both <code>prefetch</code> and <code>prerender</code>, as shown in the example below:</p>
<pre>
&lt;link rel=&quot;prefetch&quot; href=&quot;http://www.example.com/&quot;&gt; &lt;!-- Firefox --&gt;
&lt;link rel=&quot;prerender&quot; href=&quot;http://www.example.com/&quot;&gt; &lt;!-- Chrome --&gt;
</pre>
<h2>Prefetching pages on your WordPress blog</h2>
<p>As I know most of my readers are WordPress users, I thought about a WordPress-specific example of HTML5 prefetching. A blog is typically the kind of website where prefetching can be very useful: On many situations, it is possible to &#8220;guess&#8221; which page the visitor will want to read next.</p>
<p>For example, if a visitor is currently having a look to the second page of your archives, it is highly possible that he&#8217;ll read the third page next. The following code snippet (Courtesy of <a href="http://www.markensysteme.de/wordpress/prerender-link-wordpress-google-chrome/004357/">Bernd</a>) is ready to use: Just paste it into the <code>header.php</code> file of your theme in order to prefetch next archive pages.</p>
<pre>
&lt;?php if (is_archive() &amp;&amp; ($paged &gt; 1) &amp;&amp; ($paged &lt; $wp_query-&gt;max_num_pages)) { ?&gt;
&lt;link rel=&quot;prefetch&quot; href=&quot;&lt;?php echo get_next_posts_page_link(); ?&gt;&quot;&gt;
&lt;link rel=&quot;prerender&quot; href=&quot;&lt;?php echo get_next_posts_page_link(); ?&gt;&quot;&gt;
&lt;?php } ?&gt;
</pre>
<p>Of course, the version above can be enhanced according to your site own needs. According to my analytics, most people comes to my site on an article page like this one, and then, have a look to the home page. So, it can be great to add a new condition to the code above and prefetch the home page when the visitor is reading an article.</p>
<pre>
&lt;?php if (is_archive() &amp;&amp; ($paged &gt; 1) &amp;&amp; ($paged &lt; $wp_query-&gt;max_num_pages)) { ?&gt;
&lt;link rel=&quot;prefetch&quot; href=&quot;&lt;?php echo get_next_posts_page_link(); ?&gt;&quot;&gt;
&lt;link rel=&quot;prerender&quot; href=&quot;&lt;?php echo get_next_posts_page_link(); ?&gt;&quot;&gt;
&lt;?php } elseif (is_singular()) { ?&gt;
&lt;link rel=&quot;prefetch&quot; href=&quot;&lt;?php bloginfo(&#39;home&#39;); ?&gt;&quot;&gt;
&lt;link rel=&quot;prerender&quot; href=&quot;&lt;?php bloginfo(&#39;home&#39;); ?&gt;&quot;&gt;
&lt;?php } ?&gt;
</pre>
<h2>Prefetching using jQuery</h2>
<p>Now that we saw what prefetching can do for you, what about using jQuery to automatically prefetch each link with the prefetch class? That&#8217;s exactly what the snippet below do. Simply paste it to your website, and then add a <code>prefetch</code> class to each link you&#8217;d like to prefetch. </p>
<pre>
// create an object named &quot;app&quot; which we can define methods on
var app = {
    // returns an array of each url to prefetch
    prefetchLinks: function(){
        // returns an array of each a.prefetch link&#39;s href
        var hrefs = $(&quot;a.prefetch&quot;).map(function(index, domElement){
            return $(this).attr(&quot;href&quot;);
        });
        // returns the array of hrefs without duplicates
        return $.unique(hrefs);
    },

    // adds a link tag to the document head for each of prefetchLinks()
    addPrefetchTags: function(){
        // for each prefetchLinks() ...
        this.prefetchLinks().each(function(index,Element){
            // create a link element...
            $(&quot;&lt;link /&gt;&quot;, {
                // with rel=prefetch and href=Element...
                rel: &quot;prefetch&quot;, href: Element
                // and append it to the end of the document head
            }).appendTo(&quot;head&quot;);
        });
    },
}
// when the document is ready...
jQuery(function(){
  // call the method we defined above.
    app.addPrefetchTags();
}
</pre>
<p>Thanks to <a href="http://handyrailstips.com/blog_posts/1-link-prefetching-with-html-5-and-jquery">Gavin Morrice</a> for this great snippet!</p>
<img src="http://feeds.feedburner.com/~r/Catswhocode/~4/nqnfQCZ0oAA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.catswhocode.com/blog/mastering-html5-prefetching/feed</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
	</channel>
</rss>

