CSS and JavaScript tools to take your website to the next level

Topcoat


Topcoat is a very neat and clean library of CSS classes specialized in form elements: buttons, checkboxes, sliders, etc. A super easy way to make your website or app look good in minutes.

Demo/Download: http://topcoat.io/

Countable.js


As you can guess, countable.js is a JavaScript function to add live paragraph, word and character counting to any HTML element. It is very small and do not rely on any JS framework.

Demo/Download: http://radlikewhoa.github.io/Countable/

iCheck


Want super-looking checkboxes and radio buttons for your new web app? Then try iCheck, a jQuery plugin which allow you to easily customize radio buttons and checkboxes. iCheck is easy to use and comes with various skins and color schemes.

Demo/Download: http://damirfoy.com/iCheck/

CSS only responsive navigation


Responsive layouts are very popular on the web right now, and this is definitely a good thing in my opinion. Here is a downloadable and reusable responsive navigation menu, made in CSS only.

Demo/Download: http://valdelama.com/css-responsive-navigation

Almost Flat UI


Based on Foundation Framework, Almost Flat UI is a complete HTML/CSS/JS framework to build your site on. It looks really clean and professional. Definitely worth a try!

Demo/Download: http://websymphony.net/almost-flat-ui/

Chart.js


Chart.js is a dependency free, lightweight and object-oriented tool to create client side graphs. It features 6 different chart types and is very easy to use.

Demo/Download: http://www.chartjs.org/

PlaceIMG


When building websites or apps, you often need placeholder images. This very handy service generates random images at the requested size. Super useful!

Demo/Download: http://placeimg.com/

jQuery PanZoom


jQuery Panzoom is a progressive plugin to create panning and zooming functionality for an element. Panzoom supports the same browsers as jQuery 2.0 and can be used with jQuery 1.9.0+ or jQuery 2.0+.

Demo/Download: https://github.com/timmywil/jquery.panzoom/

Perfect Scrollbar


If you want to be able to create perfect looking scrollbars, then you should definitely have a look to this tiny jQuery plugin. It helps you to create customized scrollbars with no css change on any original element.

Demo/Download: http://noraesae.github.io/perfect-scrollbar/

FitVids.js


A lightweight, easy-to-use jQuery plugin for fluid width video embeds. It was built by was built by Chris Coyier and Paravel.

Demo/Download: http://fitvidsjs.com/

Deal of the week: SpyBar (3 licences to win!!)

A word about Spybar

The Internet is one huge swap meet. So many sites “borrow” code or plugins from other sites to make their own that much better. And then someone else borrows from their site, and so on. Keeping up with the latest and greatest Web features is an exhausting experience, though. You can check out tons of forums, blogs, newsletters and more just to read up on the latest releases. You can also pay a ton of money to various online services to pull in stats and suggestions.

The best way, though? Just browse. Check out what your competition’s doing. If you find something you like, copy it. If only it were that easy to look beneath the hood. Well, it is. Thanks to SpyBar, you can pull in tons of useful data about any site, and you can do it all right from your Firefox or Chrome browser!

SpyBar is sold for only $7 for a limited time by Mighty Deals.

Here is a video demo of Spybar in action:

How to win a free Spybar licence!

Our partners from Mighty Deals are happy to give away 3 Spybar licences to WPRecipes readers. To enter the contest, simply leave a comment to this post to let me know you’d like to win a free Spybar licence. I’ll randomly pick 3 lucky winners on sunday using random.org. Winners will receive their prize directly in their email.

How to make translatable JavaScript strings on your WordPress theme

Simply paste the following code into your function.php file, where you generally enqueue scripts and styles. Line 4 shows how to use the wp_localize_script() function.

function prefix_enqueue_custom_script(){
	wp_register_script( 'prefix_custom_script', plugin_dir_url( __FILE__ ) .'js/custom-script.js', array( 'jquery' ) );
        wp_enqueue_script( 'prefix_custom_script' );
        wp_localize_script( 'prefix_custom_script', 'prefix_object_name', array(
		'upload' => __( 'upload', 'textdomain' ),
		'remove' => __( 'remove', 'textdomain' )
	) );
}

Thanks to Devin for this code!

How to create a directory within the uploads folder

Simply paste this code snippet on your functions.php file (or plugin file if you’re creating a plugin)

function myplugin_activate() {
    
    $upload = wp_upload_dir();
    $upload_dir = $upload['basedir'];
    $upload_dir = $upload_dir . '/mypluginfiles';
    if (! is_dir($upload_dir)) {
       mkdir( $upload_dir, 0700 );
    }
}
 
register_activation_hook( __FILE__, 'myplugin_activate' );

Thanks to Jean Galea for the snippet!

Useful snippets to protect your WordPress blog against scrapers

Force your WordPress blog to break out of frames

Some scrapers display your blog in a frame to keep advantage of your content, and show their ads in another frame in order to try to make a few bucks. This code will force your blog to break out of the frames, so the visitor will only see your blog, not the scraper site.

Just paste the code below into your functions.php file, save it, and you’re done.

// Break Out of Frames for WordPress
function break_out_of_frames() {
	if (!is_preview()) {
		echo "\n<script type=\"text/javascript\">";
		echo "\n<!--";
		echo "\nif (parent.frames.length > 0) { parent.location.href = location.href; }";
		echo "\n-->";
		echo "\n</script>\n\n";
	}
}
add_action('wp_head', 'break_out_of_frames');

Source: http://wp-mix.com/break-out-of-frames-wordpress/

Protect your blog against image hotlinking

Most scrapers simply use your RSS feed and display it on their site, which means that they also use your original images on their sites, and consume your server bandwidth for their own websites. So you can definitely use this to inform the reader that he’s reading an article stolen from another blog.

Let’s create a small image saying something like “This article has been stolen from www.yoursite.com”. and upload it on your blog server. Then, edit your .htaccess file, (located in your WordPress blog root directory) and append this code to it:

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 "don't hotlink" image url
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]

Here is a funny example of this technique in action:

Source: http://www.wprecipes.com/how-to-protect-your-wordpress-blog-from-hotlinking

Automatically add a link to your post title

As the majority of content thieves are using automatic scraping tools, they’ll scrap all of your content, including the post title. A good way to discourage scrapers is to automatically put a link on your post titles, so each stolen post will automatically link to your original post.

To do so in WordPress, simply open your single.php file and locate where the title is displayed. Then, replace the code by the following:

<h1>
  <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</h1>

Source: http://www.catswhoblog.com/how-to-protect-your-blog-from-content-thieves

Automatically add a link to your original posts using RSS feed

Another useful way to fight back against content theft is to automatically insert a copyright notice with a backlink to the original post on each RSS item. That way, scrapers who use your RSS feed to publish your content on their own sites automatically will also publish your copyright notice and backlink!

Simply add the code below to your functions.php file. Copyright notice can be customized on line 4.

// add custom feed content
function add_feed_content($content) {
	if(is_feed()) {
		$content .= '<p>This article is copyright &copy; '.date('Y').'&nbsp;'.bloginfo('name').'</p>';
	}
	return $content;
}
add_filter('the_excerpt_rss', 'add_feed_content');
add_filter('the_content', 'add_feed_content');

Source: http://digwp.com/2012/10/customizing-wordpress-feeds/

Create a custom RSS feed

While the technique above is good, it only display a small notice at the bottom of your posts. You might want a more in-depth solution, which allow you to limit the number of characters appearing in each RSS feed item.

Here is a ready to use WordPress page template that you can easily customize to fit your specific needs.

<?php
/*
Template Name: Custom Feed
*/

$numposts = 5;

function yoast_rss_date( $timestamp = null ) {
  $timestamp = ($timestamp==null) ? time() : $timestamp;
  echo date(DATE_RSS, $timestamp);
}

function yoast_rss_text_limit($string, $length, $replacer = '...') { 
  $string = strip_tags($string);
  if(strlen($string) > $length) 
    return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;   
  return $string; 
}

$posts = query_posts('showposts='.$numposts);

$lastpost = $numposts - 1;

header("Content-Type: application/rss+xml; charset=UTF-8");
echo '<?xml version="1.0"?>';
?><rss version="2.0">
<channel>
  <title>Yoast E-mail Update</title>
  <link>http://yoast.com/</link>
  <description>The latest blog posts from Yoast.com.</description>
  <language>en-us</language>
  <pubDate><?php yoast_rss_date( strtotime($ps[$lastpost]->post_date_gmt) ); ?></pubDate>
  <lastBuildDate><?php yoast_rss_date( strtotime($ps[$lastpost]->post_date_gmt) ); ?></lastBuildDate>
  <managingEditor>[email protected]</managingEditor>
<?php foreach ($posts as $post) { ?>
  <item>
    <title><?php echo get_the_title($post->ID); ?></title>
    <link><?php echo get_permalink($post->ID); ?></link>
    <description><?php echo '<![CDATA['.yoast_rss_text_limit($post->post_content, 500).'<br/><br/>Keep on reading: <a href="'.get_permalink($post->ID).'">'.get_the_title($post->ID).'</a>'.']]>';  ?></description>
    <pubDate><?php yoast_rss_date( strtotime($post->post_date_gmt) ); ?></pubDate>
    <guid><?php echo get_permalink($post->ID); ?></guid>
  </item>
<?php } ?>
</channel>
</rss>

Source: http://yoast.com/custom-rss-feeds-wordpress/

How to display an author bio excerpt on your WordPress blog

The first thing to do is to create the function. To do so, paste the following code into your functions.php file:

<?php
	function author_excerpt (){	                     					
		$word_limit = 20; // Limit the number of words
		$more_txt = 'read more about:'; // The read more text
		$txt_end = '...'; // Display text end 
		$authorName = get_the_author();
		$authorUrl = get_author_posts_url( get_the_author_meta('ID'));
		$authorDescription = explode(" ", get_the_author_meta('description'));
		$displayAuthorPageLink = count($authorDescription) > $word_limit ? $txt_end.'<br /> '.$more_txt.' <a href="'.$authorUrl.'">'.$authorName.'</a>' : '' ;
		$authorDescriptionShort = array_slice($authorDescription, 0, ($word_limit));
		return (implode($authorDescriptionShort, ' ')).$displayAuthorPageLink; 		
	}
?>

Once done, simply call the function when needed, as shown below:

<?php  if (function_exists('author_excerpt')){echo author_excerpt();} ?>

Thanks to Tim Marcher for the tip!

How to detect a comments page on your WordPress blog

Simply put the following code anywhere on your theme files. If you’re on a comment page, the conditional statement will return true, so any code within brackets will be executed.

$cpage = get_query_var( 'cpage' );
if ( is_singular() && $cpage > 0 ){
    // Your code here
}

This code works on posts, pages, attachments as well as all custom post_types.

Thanks to Daniel Roch for the cool tip!

How to force your WordPress blog to break out of frames

Nothing complicated, just paste the code below into your functions.php file, save it, and you’re done.

// Break Out of Frames for WordPress
function break_out_of_frames() {
	if (!is_preview()) {
		echo "\n<script type=\"text/javascript\">";
		echo "\n<!--";
		echo "\nif (parent.frames.length > 0) { parent.location.href = location.href; }";
		echo "\n-->";
		echo "\n</script>\n\n";
	}
}
add_action('wp_head', 'break_out_of_frames');

Thanks to WP Mix for this very handy tip!

Hacks and snippets to enhance WordPress search engine

Redirect to first post if only one post is found

Let’s start with a handy snippet that will automatically redirect the reader to the post if only one post is found. Simply paste it in your functions.php file and you’re done.

add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
        }
    }
}

Source: http://www.paulund.co.uk/redirect-search-results…

Display the number of results in WordPress search

When a search is done on your blog, WordPress does not return the number of results found. Though, this can be useful for the person who made the search.

In order to display the number of results, open your search.php file. In it, search for the following:

<h2 class="pagetitle">Search Results</h2>

Now replace it with:

<h2 class="pagetitle">Search Results for <?php 
/* Search Count */ 
$allsearch = &new WP_Query("s=$s&showposts=-1"); 
$key = wp_specialchars($s, 1); 
$count = $allsearch->post_count; _e(''); 
_e('<span class="search-terms">'); 
echo $key; _e('</span>'); _e(' — '); 
echo $count . ' '; _e('articles'); 

wp_reset_query(); ?></h2>

Source: http://www.problogdesign.com/wordpress/3-codes-for-a-far-better…

Enlight searched text in search results

Here is an easy way to make your search results more user-friendly: Enlight searched text.
To do so, open your search.php file and find the the_title() function. Replace it with:

echo $title;

Now, just before the line you just modified, add this code:

<?php
	$title 	= get_the_title();
	$keys= explode(" ",$s);
	$title 	= preg_replace('/('.implode('|', $keys) .')/iu',
		'<strong class="search-excerpt"></strong>',
		$title);
?>

Save the search.php file and open style.css. Append the following line to it:

strong.search-excerpt { background: yellow; }

That’s all. Better, isn’t it?

Source: http://yoast.com/wordpress-search/

Limit posts per page on search

By default, WordPress outputs 10 posts per page on the search results page. If you need to change this number, just paste the following code in your functions.php file. Replace the number on line 3 by the desired number of posts to be displayed.

function limit_posts_per_search_page() {
	if ( is_search() )
		set_query_var('posts_per_archive_page', 20); 
}

add_filter('pre_get_posts', 'limit_posts_per_search_page');

Source: http://wordpress.org/support/topic/limit-post-per-search-page

Search within post type only

If you want to force the search engine to search only within a specific post type, here is the solution. Paste the code below into your functions.php file after you changed the post type name on line 4.

function SearchFilter($query) {
  if ($query->is_search) {
    // Insert the specific post type you want to search
    $query->set('post_type', 'feeds');
  }
  return $query;
}
 
// This filter will jump into the loop and arrange our results before they're returned
add_filter('pre_get_posts','SearchFilter');

Source: http://www.hongkiat.com/blog/wordpress-search-plugin-snippet/

Limit search to specific categories

Is it also possible to limit search to specific categories. To do so, just replace the categories IDs on line 3 and paste the following code on your search.php template:

<?php if( is_search() )  :
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts("s=$s&paged=$paged&cat=1,2,3");
endif; ?>

Source: http://www.wprecipes.com/how-to-limit-search-to-specific-categories

Completely shut down WordPress search

Although search is a really useful feature on most websites, sometimes you simply don’t need it at all. Did you knew that you could completely shut down WordPress search? Just include the function below in your functions.php file.

function fb_filter_query( $query, $error = true ) {
    if ( is_search() ) {
        $query->is_search = false;
        $query->query_vars[s] = false;
        $query->query[s] = false;
 
        // to error
        if ( $error == true )
            $query->is_404 = true;
    }
}
 
add_action( 'parse_query', 'fb_filter_query' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

Source: http://wpengineer.com/1042/disable-wordpress-search/

Make your search results unlimited

As I already stated before, the fact that WordPress displays 10 posts by default on the search results page can be annoying. If you’d like to display unlimited search results on the same page, here’s an easy way to do it.

In search.php, find the code below:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

Once you found it, replace it by this:

<?php $posts=query_posts($query_string . '&posts_per_page=-1'); ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

That’s all. You’re done!
Source: http://wphacks.com/how-to-make-wordpress-search-results-unlimited/

How to redirect to post if search results only returns one post

Just paste the following code snippet into your functions.php file:

add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
        }
    }
}

Thanks to Paulund.co.uk for the snippet!

Cross browser compatible HTML5 videos

Step 1: Preparing files

The first thing to do is to make sure your files are in the right format for HTML5 video playing. Right now, there’s no standard format so you’ll have to have multiple versions of the same file in order to serve the right format to the client browser. This is indeed the biggest problem with HTML5 videos right now.

You’ll need the 3 following formats: The first is .mp4 (or .m4v) which is used on Apple products such as iPads, Safari, etc. The second format needed is .ogv, an open-source format used by Firefox. And the last one is .webm.

Converting your file into those formats is pretty easy if you use this very handy tool named Video Converter. You have nothing to install on your computer, simply upload your video, choose the desired output format, and you’re done!

Now that you have your video in the required formats, let’s start coding. You’ll see, it’s very easy.

Step 2: Coding the player

Below is the basic code for displaying a HTML5 video on a web page. Please note that in order to have the video properly displayed on iPad, you must start with the .mp4 video in the src list.

On line 5, I have added a download link for older browser who don’t recognize the <video> tag.

<video width="800" height="374">
	<source src="my_video.mp4" type="video/mp4" />
	<source src="my_video.ogv" type="video/ogg" />
	<source src="my_video.webm" type="video/webm" />
	Video tag not supported. Download the video <a href="video.webm"&gthere</a&gt.
</video>

A very important thing to remember is to make sure your server is serving video files with the correct MIME type in the Content-Type header. To make sure it will, open your site .htaccess file (don’t forget to do a backup before any modification) and add the lines below:

AddType video/ogg .ogv
AddType video/mp4 .mp4
AddType video/webm .webm

Also, various attributes can be used with the <video> element, for example to autoplay the video, loop it, or automatically display some controls. For the full reference, please see the w3 site.

Step 3: Creating a fallback for older browsers

Now, you have a super cool HTML5 video player. But the problem is that some older browsers don’t support any HTML video at all. For those browsers, the only solution is to use a Flash fallback.

As the purpose of this tutorial is not to show how to built a Flash video player, I’m assuming that you have your video in the .flv format (named video.flv below) as well as a flash .flv player (named fallback.swf).

As you can see below, I have added my <object> tag inside the <video> tag. That’s simple as that!

<video width="800" height="374">
	<source src="my_video.mp4" type="video/mp4" />
	<source src="my_video.ogv" type="video/ogg" />

	<object width="800" height="374" type="application/x-shockwave-flash" data="fallback.swf">
		<param name="movie" value="fallback.swf" />
		<param name="flashvars" value="autostart=true&amp;file=video.flv" />
	</object>

</video> 

How to directly include Typekit fonts on your WordPress theme

Edit the code below and update the .js file path on line 2. Then, simple paste it on your functions.php file. Save the file, and you’re done!

function theme_typekit() {
    wp_enqueue_script( 'theme_typekit', '//use.typekit.net/xxxxxxx.js');
}
add_action( 'wp_enqueue_scripts', 'theme_typekit' );

function light_typekit_inline() {
  if ( wp_script_is( 'theme_typekit', 'done' ) ) { ?>
  	<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<?php }
}
add_action( 'wp_head', 'theme_typekit_inline' );

Thanks to Devin for this useful tip!

Themes4All giveaway: 3 premium themes to win!

About Themes4All.com

Our sponsor is Themes4All.com, which is a newcomer in the WordPress premium theme business. They specialize in low cost/high quality themes.
They already released 20+ themes, each priced $10. Click here to view the available themes.

How to join the giveaway?

Joining the giveaway is free and easy: First, go to Themes4All.com and create a free account. Registration grant you access to a free theme each month. In March, the free theme is Bryder.

Once done, simply add a comment to this post to let me know which theme you’d like to win. In one week (Thursday April 4, 2013), I’ll randomly pick 3 winners. Each of theme will receive the chosen theme by email, from the Themes4All.com staff.

Good luck everyone!

Super useful jQuery plugins for responsive web design

SlabText.js


SlabText is a jQuery plugin that splits headlines into rows before resizing each row to fill the available horizontal space. Basically, it means that your headline will always look great whatever of the client screen size.
Download: http://www.frequency-decoder.com/2012/01/08/slabtext-a-jquery-plugin…

jQuery Masonry


Masonry is a dynamic grid layout plugin for jQuery. Think of it as the flip-side of CSS floats. Whereas floating arranges elements horizontally then vertically, Masonry arranges elements vertically, positioning each element in the next open spot in the grid.
Download: http://masonry.desandro.com/

TinyNav.js


TinyNav.js is a super useful jQuery plugin which allows you to automatically turn a navigation menu into a select for small devices such as iPhones. A must have!
Download: http://tinynav.viljamis.com/

FitText.js


FitText is a simple jQuery plugin that automatically make a text fit the width of its parent element. Perfect for awesome, responsive headlines!
Download: http://fittextjs.com/

Breakpoints.js


Simply define breakpoints for your responsive design, and Breakpoints.js will fire custom events when the browser enters and/or exits that breakpoint. Very useful on complicated layouts!
Download: http://xoxco.com/projects/code/breakpoints/

ResponsiveSlides.js


Slideshows are very popular among the web. Though, forcing them to fit any screen size can be a little tricky. ResponsiveSlides.js allow you to create responsive slideshows, which will look great whatever on any device.
Download: http://responsive-slides.viljamis.com/

Flare


Flare is another jQuery plugin for building responsive and full width slideshows. It is not free but it is absolutely worth $10 as it is very easy to use and visually pleasant.
Download: http://is.gd/flarecwc

FitVids.js


A lightweight, easy-to-use jQuery plugin for fluid width video embeds. It was built by was built by Chris Coyier and Paravel.
Download: http://fitvidsjs.com/

Responsive tables


Does your tables break your responsive layout? If yes, here is a simple JS/CSS combo that will let your tables adapt to small device screens without everything going to hell. A must have for any tables!
Download: http://www.zurb.com/playground/responsive-tables

jq-idealforms


Ideal Forms is the ultimate framework for building and validating responsive HTML5 forms. It is super easy to use.
Download: http://elclanrs.github.com/jq-idealforms/