How to use your Gravatar as a favicon on your WordPress blog

First, edit the following function by adding your email adress on line 3, then paste it on your functions.php file.

function GravatarAsFavicon() {
	//We need to establish the hashed value of your email address
	$GetTheHash = md5(strtolower(trim('[email protected]')));
	echo 'http://www.gravatar.com/avatar/' . $GetTheHash . '?s=16';
}

Once done, open the header.php file of your theme and paste this:

<link rel="shortcut icon" href="<?php GravatarAsFavicon(); ?>" />
<link rel="apple-touch-icon" href="<?php GravatarAsFavicon(); ?>">

Thanks to Adam Whitcroft for the cool tip!

10 useful typography tips to improve your website readability

Correct line height

One of the most common web typography mistake is definitely an incorrect line height. Line height define the height of a line of text, so it have to be set according on the font size.

As a rule of thumb, I always add 7px to the font size when setting line height on texts (with 12 to 15 pixels font size)

body{
    font-size:14px;
    line-height:21px; /* 14px + 7px */
}

Correct title margins

Another common mistake is an incorrect margin around titles. A title is related to a paragraph, it is not a separator between two paragraphs. This is why a title should have a wider margin on top than on its bottom.

Don’t use too many different fonts

In order to keep your website readable and professional, you shouldn’t use more than 3 different fonts. Using too many fonts can be confusing for the reader and will make your website look cluttered.
On the other hand, using fewer fonts keeps your website clean and readable. You can use one font for headings, one for the text, and eventually another one for the logo or the subtitles.

Use monospaced fonts to display code snippets

If you’re a developer (like most persons reading this blog) you probably want to display some code snippets on your blog. If yes, please use a monospaced font to do so. So, what’s a monospaced font? It’s a font whose letters and characters each occupy the same amount of horizontal space.

So, which fonts should you use to display code snippets on a website? Courier is by far the most popular, but what about giving a try to most recent fonts such as Consolas or Monaco? And if you want even more choice, you should definitely have a look there.

Care about contrast

Even if your website have a great typography, another point to consider is contrast. If your page background is grey (#999999), then do not use a dark grey text (#333333) otherwise your content may be hard to read, especially for older people or people with visual disabilities.

Generally, excepted if your site is about hacking, black hat seo or gothic rock, you should use a light background and a dark font to keep a bright contrast and increase your site readability.

Keep underlined text for links

Since I’ve started using the internet twelve years ago, the default style applied to links by browsers is a blue text with an underline. Althought the blue is often changed to another color, the underline has been since recognized as the generic style for links. This is why you should never use underlined text for other things than links. Otherwise, this can be very confusing for your readers.

Create a library of styles

A simple and effective way to make your website visually stunning is create specific styles for specific usages. For example, what about creating a .warning CSS class to display warnings to your readers?

Hierarchize titles and text

In order to improve readability, creating a hierarchy consisting of titles, intro paragraphs and regular text is important because they allow your readers to visualize your articles and quickly access to the part that they’re interested in.

Don’t be afraid of white space

One of the best typography tip I’ve received is “Don’t be afraid of white space”. White space is not blank space nor unused space, it make your design clutter-free and professional. Many people love Apple’s website for that reason: It’s sophisticated but simple, and have lots of white space.

Use the right symbols

An important point to consider if you’re looking to improve your typography is the use of the rights symbols. For example, double prime symbols are often used instead of quote symbols.
Note the difference betwen the double prime verison:

He said "Hello".

And the same text, using quote symbols:

He said “Hello„.

Better, isn’t it? If you’re a WordPress user, you’ll probably be happy to know that your favorite blogging platform automatically transform double primes into smart quotes. Otherwise, you should use HTML entities as shown below:

He said &amps;ldquo;Hello&bdquo;.

How to create custom dashboard help messages

The code have to be pasted into your functions.php file in order to work. Please edit line 4 with the desired help message.

function my_admin_help($text, $screen) {
	// Check we're only on my Settings page
	if (strcmp($screen, MY_PAGEHOOK) == 0 ) {
		$text = 'Here is some very useful information to help you use this plugin...';
		return $text;
	}
	// Let the default WP Dashboard help stuff through on other Admin pages
	return $text;
}

add_action( 'contextual_help', 'my_admin_help' );

Thanks to Studio Grasshopper for the code!

How to add .pdf support to the WordPress media manager

Paste this code into your functions.php file. Save the file, and you’re done.

function modify_post_mime_types( $post_mime_types ) {

	// select the mime type, here: 'application/pdf'
	// then we define an array with the label values

	$post_mime_types['application/pdf'] = array( __( 'PDFs' ), __( 'Manage PDFs' ), _n_noop( 'PDF <span class="count">(%s)</span>', 'PDFs <span class="count">(%s)</span>' ) );

	// then we return the $post_mime_types variable
	return $post_mime_types;

}

// Add Filter Hook
add_filter( 'post_mime_types', 'modify_post_mime_types' );

Note that this code snippet can be used for other file types as well as .swf, .avi, .mov, etc.

Thanks to WP Tuts for the nice code snippets!

How to automatically generate a QR code for your posts

Copy the following code and paste it into your single.php file, where you want the QR code to be displayed.
If you also want to provide a QR code on pages, paste the code into page.php as well.

<img src="http://api.qrserver.com/v1/create-qr-code/?size=100x100&data=<?php the_permalink(); ?>" alt="QR:  <?php the_title(); ?>"/>

Thanks to Kevin Chard for the tip!

How to define a default post thumbnail

Paste the code below into your functions.php file. Don’t forget to update the code with your default image url on line 13.

add_action( 'save_post', 'wptuts_save_thumbnail' );

function wptuts_save_thumbnail( $post_id ) {

	// Get Thumbnail
	$post_thumbnail = get_post_meta( $post_id, $key = '_thumbnail_id', $single = true );

	// Verify that post is not a revision
	if ( !wp_is_post_revision( $post_id ) ) {
		// Check if Thumbnail exists
		if ( empty( $post_thumbnail ) ) {
			// Add thumbnail to post
			update_post_meta( $post_id, $meta_key = '_thumbnail_id', $meta_value = 'http://yoursite.com/your_image_url.jpg' );
		}
	}

}

Thanks to WPTuts for the snippet!

How to easily add shortcuts to WordPress toolbar

Paste the code below into your functions.php file.

// add a link to the WP Toolbar
function custom_toolbar_link($wp_admin_bar) {
	$args = array(
		'id' => 'gmail',
		'title' => 'Gmail', 
		'href' => 'https://mail.google.com/mail/#inbox', 
		'meta' => array(
			'class' => 'gmail', 
			'title' => '[email protected]'
			)
	);
	$wp_admin_bar->add_node($args);
}
add_action('admin_bar_menu', 'custom_toolbar_link', 999);

Once done, edit the following, then save the file. You’re done!
‘id’ => ‘gmail’ — the ID of the

  • element containing the custom link
    ‘title’ => ‘Gmail’ — the anchor-text for the custom link
    ‘href’ => ‘https://mail.google.com/mail/#inbox’ — the URL for the custom link
    ‘class’ => ‘gmail’ — the class attribute for the custom link
    ‘title’ => ‘[email protected]’ — the title attribute for the custom link

    Thanks to Jeff Starr for the cool tip!

  • How to display pingbacks/trackbacks count within admin post columns

    Simply paste the code below in your functions.php file. Once saved, your pingback/trackback count is displayed within admin post columns.

    function commentCount($type = 'comments'){
    	if($type == 'trackbacks'):
    		$typeSql = 'comment_type = "trackback"';
    		$oneText = 'One :trackback';
    		$moreText = '% :trackbacks';
    		$noneText = 'No :trackbacks';
    	elseif($type == 'pingbacks'):
    		$typeSql = 'comment_type = "pingback"';
    		$oneText = 'One :pingback';
    		$moreText = '% :pingbacks';
    		$noneText = 'No :pingbacks';
    	endif;
    	global $wpdb;
        $result = $wpdb->get_var('
            SELECT
                COUNT(comment_ID)
            FROM
                '.$wpdb->comments.'
            WHERE
                '.$typeSql.' AND
                comment_approved="1" AND
                comment_post_ID= '.get_the_ID()
        );
    	if($result == 0):
    		echo str_replace('%', $result, $noneText);
    	elseif($result == 1):
    		echo str_replace('%', $result, $oneText);
    	elseif($result > 1):
    		echo str_replace('%', $result, $moreText);
    	endif;
    }
    add_filter('manage_posts_columns', 'posts_columns_counts', 1);
    add_action('manage_posts_custom_column', 'posts_custom_columns_counts', 1, 2);
    function posts_columns_counts($defaults){
        $defaults['wps_post_counts'] = __('Counts');
        return $defaults;
    }
    function posts_custom_columns_counts($column_name, $id){
    	if($column_name === 'wps_post_counts'){
    		commentCount('trackbacks'); echo "<br />";
    		commentCount('pingbacks');
              }
    }
    

    Thanks to InstantShift for this great piece of code!

    MightyDeals giveaway: bundle of 10 responsive websites templates to win!

    A word about Mighty Deals

    Mightydeals offers unbelievable deals and discounts for creative professionals.The deals include products and services that are heavily discounted, exclusively for Mighty Deals customers, usually from 50% to 90% off. Each deal stays on the site for a very limited time and is available exclusively for purchase directly through the site.

    How to enter the giveaway?

    Entering the giveaway is super simple, just leave a comment on this post. Make sure you use your real email adress as prizes will be sent to this email.

    In one week (July 3), I’ll pick 3 winners using random.org. Winners will receive their prize from Mightydeals by email.

    By the way, do not forget to visit MightyDeal’s partner Flashmint!

    WordPress dashboard hacks for developers and freelancers

    Remove menu items from WordPress admin bar

    Here is a super useful code snippet for developers who wants to prevent their clients to access some dashboard menus, such as “Plugins” or “Settings”. Paste this code into your theme functions.php file to remove menus from the admin bar.

    function wps_admin_bar() {
        global $wp_admin_bar;
        $wp_admin_bar->remove_menu('wp-logo');
        $wp_admin_bar->remove_menu('about');
        $wp_admin_bar->remove_menu('wporg');
        $wp_admin_bar->remove_menu('documentation');
        $wp_admin_bar->remove_menu('support-forums');
        $wp_admin_bar->remove_menu('feedback');
        $wp_admin_bar->remove_menu('view-site');
    }
    add_action( 'wp_before_admin_bar_render', 'wps_admin_bar' );
    

    Source: http://wpsnipp.com/index.php/functions-php/remove-menu…

    Remove the screen options tab with screen_options hook

    Don’t need the “Screen Options” button? Here is a simple hack to remove it. Paste the code below into your functions.php file, save it, and you’re done.

    function remove_screen_options(){
        return false;
    }
    add_filter('screen_options_show_screen', 'remove_screen_options');
    

    Source: http://wpsnipp.com/index.php/functions-php/chnage-default…

    Change default “Enter title here” text within post title input field

    If for some reason you need to replace the “Enter title here” text within post title input field by a custom text, here is an easy way to do it. Define a new text on line 2, then paste the code into your functions.php file.

    function title_text_input( $title ){
         return $title = 'Enter new title';
    }
    add_filter( 'enter_title_here', 'title_text_input' );
    

    Source: http://wpsnipp.com/index.php/functions-php/chnage-default…

    Change dashboard footer text

    Changing the dashboard footer text is pretty easy as well. Update the code below with your custom text on line 2, then include the snippet into your functions.php file.

    function remove_footer_admin () {
        echo "Your own text";
    } 
    
    add_filter('admin_footer_text', 'remove_footer_admin'); 
    

    Source: http://www.wprecipes.com/wordpress-tip-how-to-change-the-dashboard-footer-text

    Disable the “please update now” message in WP dashboard

    Security is indeed a crucial aspect of a website and you should always update all blogs you manage to prevent any risk of hacking. But when working with clients, sometimes you may want to hide the “please update now” message generated by WordPress when a new version is available.

    Simply add this code to your functions.php file to hide the message.

    if ( !current_user_can( 'edit_users' ) ) {
      add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
      add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
    }
    

    Source: http://www.wprecipes.com/how-to-disable-the-please-update-now-message…

    Custom login form with full screen background

    Here is a super cool code snippet that your clients will definitely love: a custom login form with a full screen background. Click here for a demo. Once again, the code goes to your functions.php file.

    Please note that I left the CSS code “as it” so you can have a look at it, but on a production site you should definitely use an external stylesheet instead.

    function login_enqueue_scripts(){
    	echo '
    		<div class="background-cover"></div>
    		<style type="text/css" media="screen">
    			.background-cover{
    				background:url('.get_bloginfo('template_directory').'/images/background) no-repeat center center fixed; 
    				-webkit-background-size: cover; 
    				-moz-background-size: cover; 
    				-o-background-size: cover; 
    				background-size: cover; 
    				position:fixed; 
    				top:0; 
    				left:0; 
    				z-index:10; 
    				overflow: hidden; 
    				width: 100%; 
    				height:100%;
    			} 
    			#login{ z-index:9999; position:relative; }
    			.login form { box-shadow: 0px 0px 0px 0px !important; }
    			.login h1 a { background:url('.get_bloginfo('template_directory').'/images/logo.png) no-repeat center top !important; } 
    			input.button-primary, button.button-primary, a.button-primary{ 
    				border-radius: 3px !important; 						background:url('.get_bloginfo('template_directory').'/images/button.jpg); 
    					border:none !important;
    					font-weight:normal !important;
    					text-shadow:none !important;
    				}
    				.button:active, .submit input:active, .button-secondary:active {
    					background:#96C800 !important; 
    					text-shadow: none !important;
    				}
    				.login #nav a, .login #backtoblog a {
    					color:#fff !important;
    					text-shadow: none !important;
    				}
    				.login #nav a:hover, .login #backtoblog a:hover{
    					color:#96C800 !important;
    					text-shadow: none !important;
    				}
    				.login #nav, .login #backtoblog{
    					text-shadow: none !important;
    				}
    			</style>
    		';
    	}
    add_action( 'login_enqueue_scripts', 'login_enqueue_scripts' );
    

    Source: http://www.catswhocode.com/blog/snippets/custom-wp-login…

    Disable theme switching

    The best way to prevent your clients from switching theme is definitely by disabling theme switching. Paste the following code into functions.php and your clients will not be able to switch themes anymore.

    add_action('admin_init', 'slt_lock_theme');
    function slt_lock_theme() {
    	global $submenu, $userdata;
    	get_currentuserinfo();
    	if ($userdata->ID != 1) {
    		unset($submenu['themes.php'][5]);
    		unset($submenu['themes.php'][15]);
    	}
    }
    

    Source: http://www.wprecipes.com/how-to-easily-disable-theme-changing

    Change WordPress dashboard colors

    If you ever wanted to be able to change WordPress dashboard colors (as well as font or even display) without having to edit WordPress core files, you’ll like this hack for sure.
    The following example features a basic style change (grey header is replaced by a blue one) but you can easily add as many styles as you wish within the <style> and </style> tags.

    function custom_colors() {
       echo '<style type="text/css">#wphead{background:#069}</style>';
    }
    
    add_action('admin_head', 'custom_colors');
    

    Create custom help messages

    If you’re building a site for a client and they have some problems with some parts of the dashboard, a good idea is to provide contextual help to the client.
    The following hack will allow you to add a custom help messages for the blog admin. As usual, you only have to paste the code into your functions.php file.

    function my_admin_help($text, $screen) {
    	// Check we're only on my Settings page
    	if (strcmp($screen, MY_PAGEHOOK) == 0 ) {
    
    		$text = 'Here is some very useful information to help you use this plugin...';
    		return $text;
    	}
    	// Let the default WP Dashboard help stuff through on other Admin pages
    	return $text;
    }
    
    add_action( 'contextual_help', 'my_admin_help' );
    

    Source: http://www.studiograsshopper.ch/code-snippets/wordpress-action-hook-contextual-help/

    Change WordPress default FROM email address

    If you want to change WordPress default FROM email adress, simply paste the following snippet into your functions.php file. Don’t forget to put the desired email adress on line 5 and desired name on line 8.

    add_filter('wp_mail_from', 'new_mail_from');
    add_filter('wp_mail_from_name', 'new_mail_from_name');
    
    function new_mail_from($old) {
     return '[email protected]';
    }
    function new_mail_from_name($old) {
     return 'Your Blog Name';
    }
    

    Source: http://www.wprecipes.com/how-to-change-wordpress-default-from…

    How to automatically add rel=”lightbox” to all images embedded in a post

    Paste the following code snippet in your functions.php file. Once done, a rel=”lightbox” attribute will be automatically added to all images embedded in a post.

    add_filter('the_content', 'my_addlightboxrel');
    function my_addlightboxrel($content) {
           global $post;
           $pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
           $replacement = '<a$1href=$2$3.$4$5 rel="lightbox" title="'.$post->post_title.'"$6>';
           $content = preg_replace($pattern, $replacement, $content);
           return $content;
    }
    

    Thanks to Tyler Longren for the snippet!

    Easily embed and share Github gists on your WordPress blog

    Paste the following code into your functions.php file. Once done, simply paste the URL of a Github gist into a post or page. The gist will be automatically embedded in your blog.

    **
     * Usage:
     * Paste a gist link into a blog post or page and it will be embedded eg:
     * https://gist.github.com/2926827
     *
     * If a gist has multiple files you can select one using a url in the following format:
     * https://gist.github.com/2926827?file=embed-gist.php
     */
    wp_embed_register_handler( 'gist', '/https:\/\/gist\.github\.com\/(\d+)(\?file=.*)?/i', 'wp_embed_handler_gist' );
    
    function wp_embed_handler_gist( $matches, $attr, $url, $rawattr ) {
    
    	$embed = sprintf(
    			'<script src="https://gist.github.com/%1$s.js%2$s"></script>',
    			esc_attr($matches[1]),
    			esc_attr($matches[2])
    			);
    
    	return apply_filters( 'embed_gist', $embed, $matches, $attr, $url, $rawattr );
    }
    

    Thanks to Robert O’Rourke for this handy piece of code!

    How to create a custom database error page

    Paste the code below into a new file. Name it db-error.php and save it on your wp-content directory. In case of a database error, WordPress will automatically use this file.

    <?php // custom WordPress database error page
    
      header('HTTP/1.1 503 Service Temporarily Unavailable');
      header('Status: 503 Service Temporarily Unavailable');
      header('Retry-After: 600'); // 1 hour = 3600 seconds
    
      // If you wish to email yourself upon an error
      // mail("[email protected]", "Database Error", "There is a problem with the database!", "From: Db Error Watching");
    
    ?>
    
    <!DOCTYPE HTML>
    <html>
    <head>
    <title>Database Error</title>
    <style>
    body { padding: 20px; background: red; color: white; font-size: 60px; }
    </style>
    </head>
    <body>
      You got problems.
    </body>
    </html>
    

    Thanks to CSS Tricks for the tip!

    Best practices for efficient HTML5 coding

    Use a generator


    When building a website, you often start with a base template that you customize to fit your needs. Instead of writing all your HTML5 code from scratch, you can save time by using one of those very useful online HTML5 generators. Using them is definitely easy: You fill a basic form to set up desired options, you click on a button and a basic HTML5 template is available for you to use.

    There are quite a lot of HTML5 generators, but my favorites are definitely SwitchToHTML5 and Shikiryu generator, which have more options.

    And if you prefer a ready to use template, the HTML5 Boilerplate is a must have.

    Use a cheat sheet


    With new additions or changes to HTML5 happening quite frequently, it can become hard to remember all the new various features. One of the best tools to keep an eye on HTML5 tags and property is definitely those up to date cheat sheets, created by InMotion Hosting.

    The cheat sheets are broken up into three easy to print images: Tags, Event Handler Content Attributes and Browser Support.
    All three cheat sheets can be downloaded here.

    Be careful with compatibility issues


    HTML5 is a new technology. You can already use it but right now, but you have to remember that several specifications have not been implemented in some browsers.

    Can I Use.com is definitely a website to have in your bookmarks if you’re coding HTML5 websites. It is the most complete tool to quickly know if an element is supported by a specific browser. CanIUse.com also contains compatibility charts for CSS3, SVG and JavaScript.

    Know how to enable HTML5 on older versions of IE

    Internet Explorer have always been a pain for web developers and designers. I’m pretty sure that most of you remember when in 2006 or 2007 we had to take lots of time to get things working (almost) correctly on IE6… Although IE’s newer versions are a lot better than what IE used to be, the IE developer nightmare is not over yet. In fact, IE 8 and below do not understand HTML5 at all.

    The good news is that a small script allow you to enable HTML5 on IE 8 and older. Using this script is pretty simple, just paste the following code in the <head> section of your HTML5 document:

    <!--[if lt IE 9]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    

    Another very useful tool to consider is Modernizr, a complete JavaScript library that helps you build HTML5 website that works perfectly in all browsers.

    Using Modernizr is pretty easy. Just go to this page to specify which HTML5/CSS3 properties you plan to use, then download the generated script. Include it in the <head> section of your document, and you’re done. Modernizr will detect which features can be used in the client browser and will add classes to the <html> tag. If a feature is supported by the browser, that feature is added by name as a class to the tag. If the feature is not supported, the class is added and prepended with “no-”.

    Use elements correctly

    Before HTML5, we used to code websites using lots of <div> elements. The biggest problem with this technique is definitely that source code can quickly become hard to read. This is why HTML5 introduced new tags to be used instead of the good old <div>.

    Those new tags includes header, footer, article, section, aside, nav and more. A basic, but semantically correct HTML5 document should look like the following:

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title></title>
    </head>
    <body>
      <header>
    	...
      </header>
    
      <div role="main">
    	...
      </div>
    
      <footer>
    	...
      </footer>
    </body>
    </html>
    

    Validate your code


    After coding a page in HTML5, the fastest and most efficient way to make sure that your code is semantically correct is indeed by validating it. The good old W3C validator can validate your HTML5 pages and show you if you made any mistake. A great tool for quality check!