Amazing CSS3 techniques you should know

Color animate any shape with CSS3 and a PNG


Let’s start this compilation with an interesting effect created using only CSS3: A png image with a changing background. The background is using CSS3 transitions. Not the kind of effect you’ll put on your website, but definitely an interesting demo of what CSS3 can do.
View source: http://jsfiddle.net/chriscoyier/vhKhT/

Create adaptable layout using CSS3 media queries


CSS3 media queries allow you to adapt a web layout to the browser width. Which means that you can easily create an adaptable layout that fits both big displays and mobile devices. You probably already checked my article on that subject, so I’ve picked another informative tutorial written by webdesigner Nick La. A technique any web developer should know!
View tutorial: http://webdesignerwall.com/tutorials/adaptive-mobile-design-with-css3-media-queries

Dim entire page when certain link is rolled over, css way


Very cool for web apps: Once a particular link is rolled over, the rest of the page is dimmed. This technique may also be a starting point for other great experiments.
View source: http://jsfiddle.net/chriscoyier/pVsKe/1/

Clipping text with CSS3 text-overflow


text-overflow is a new CSS3 property which allows you to define how to handle a text which is bigger than its container. This example will show you anything you need to know about this property. Unfortunely, as I’m writing this post text-overflow is only supported by Opera and IE9.
View source: http://www.456bereastreet.com/archive/201105/clipping_text_with_css3_text-overflow/

Full Browser Width Bars


Another goldie from Chris Coyier: In this tutorial, he’ll teach you how to create full browser width bars easily.
View source: http://css-tricks.com/examples/FullBrowserWidthBars/

CSS Mask-Image & Text


A great text effect using CSS3 and mask images. Unfortunately, the effect is not supported by some browsers, but it degrades gracefully. This effect will probably be very popular when CSS3 will be fully supported by all major browsers.
View source: http://trentwalton.com/2011/05/19/mask-image-text/

Image slider with CSS3 transitions


Who’s never heard of JavaScript sliders, such as NivoSlider? That kind of effect is very popular for the past two or three years. With the new CSS3 animations, it is now possible to enhance transitions between images. This tool, called Flux Slider, supports either jQuery or Zepto.js. It works on any browser supporting CSS3 transitions.
View source: http://blog.joelambert.co.uk/2011/05/05/flux-slider-css3-animation-based-image-transitions/

Flared Borders with CSS


Remember that time when you had to create images just to display a box with rounded corners? Thanks to the border-radius, this painful process is no longer needed. This very cool tutorial will show you how to create an element that flares into another using only CSS. The whole code degrades gracefully in older browsers.
View source: http://orderedlist.com/blog/articles/flared-borders-with-css/

WordPress tip: Quick maintenance mode

Paste the following code into your functions.php file. Don’t forget to remove the code once you’re done with maintenance!

function wpr_maintenance_mode() {
    if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) {
        wp_die('Maintenance, please come back soon.');
    }
}
add_action('get_header', 'wpr_maintenance_mode');

Thanks to Skyje for the cool tip!

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

WordPress tip: Quick maintenance mode

10 useful .htaccess snippets to have in your toolbox

Before editing your .htaccess file, always make a backup so you can restore it if needed.

Remove www in url

For SEO reasons, you might always remove (or use) the www prefix in your urls. The following snippet will remove the www from your website url and redirect any url with the www to the non-www version.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^your-site.com$ [NC]
RewriteRule ^(.*)$ http://your-site.com/$1 [L,R=301]

Source: http://css-tricks.com/snippets/htaccess/www-no-www/

Prevent hotlinking

Hotlinking is a bad practice that consist of using the images from another site on yours. When you’re hotlinked by someone else, your bandwidth is used for someone else profit. Of course, you may want to prevent hotlinkers. Just add the following snippet to your .htaccess file after replacing the example urls by your own urls.

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]

Source:

Redirect all WordPress feeds to feedburner

Most bloggers are using Feedburner, a web service that lets you know how many people are reading your blog via feeds. If you’re using WordPress, you should redirect all WordPress feeds (rss, atom, etc) to your feedburner feed. Modify lines 2 and 3, and then paste this code to your .htaccess file.

<IfModule mod_alias.c>
 RedirectMatch 301 /feed/(atom|rdf|rss|rss2)/?$ http://feedburner.com/yourfeed/
 RedirectMatch 301 /comments/feed/(atom|rdf|rss|rss2)/?$ http://feedburner.com/yourfeed/
</IfModule>

Source: http://www.wprecipes.com/how-to-redirect-wordpress-rss-feeds-to-feedburner-with-htaccess

Create custom error pages

Tired of the old errors pages of your site? Just create some html files with the look you want, upload them to your server, and add the following to your .htaccess file:

ErrorDocument 400 /errors/badrequest.html
ErrorDocument 401 /errors/authreqd.html
ErrorDocument 403 /errors/forbid.html
ErrorDocument 404 /errors/notfound.html
ErrorDocument 500 /errors/serverr.html

Source: http://css-tricks.com/snippets/htaccess/custom-error-pages/

Force download of specific files

When offering some files such as mp3s, eps or xls, for download on your site, you may force download instead of letting the browser decide what to do.
This snippet will force the download of .xls and .eps files from your server.

<Files *.xls>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>
<Files *.eps>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>

Source: http://www.givegoodweb.com/post/30/forcing-a-download-with-apache-and-htaccess

Log PHP errors

This snippet is an interesting way to log errors from your php file into a log file. Just create a php_error.log file somewhere on your server, and add the snippet to your .htaccess file. Don’t forget to modify the log file location on line 7.

# 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

Source: http://css-tricks.com/snippets/htaccess/php-error-logging/

Remove file extensions from urls

File extensions may be useful to developers, but there’s absolutely no need for your site visitors to be able to see them. This snippet will remove the .html extension on any html files. Of course, this code can be easily adapted to remove extensions from other file extensions such as php.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
# Replace html with your file extension, eg: php, htm, asp

Source: http://eisabainyo.net/weblog/2007/08/19/removing-file-extension-via-htaccess

Prevent directory listing

On your web server, when a directory do not have an index file, Apache automatically create a list of all files from the current directory. If you do not wish that anyone can see which files are on your server, just add the following code to your .htaccess file to prevent automatic directory listing.

Options -Indexes

Reduce pages weight by compressing static data

Do you know that it is possible to send compressed data to the visitors, which will be decompressed by the client? This code will definitely save you (and your visitor) bandwidth and reduce your pages weight.

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml text/javascript text/css application/x-javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4.0[678] no-gzip
BrowserMatch bMSIE !no-gzip !gzip-only-text/html

Automatically add utf-8 charset to files

In order to avoid encoding problems, you can force a specific encoding directly on your .htaccess file. That way, you’ll ensure that your html documents will always render correctly, even if your forget to add a <meta http-equiv="Content-Type"> directive on your html pages.

<FilesMatch "\.(htm|html|css|js)$">
AddDefaultCharset UTF-8
</FilesMatch>

Source: http://www.askapache.com/htaccess/setting-charset-in-htaccess.html

How to create offline HTML5 web apps in 5 easy steps

Getting started

1 – Add HTML5 doctype

The first thing to do is create a valid HTML5 document. The HTML5 doctype is easier to remember than ones used for xhtml:

<!DOCTYPE html>
<html>
  ...

Create a file named index.html, or get the example files from my CSS3 media queries article to use as a basis for this tutorial.
In case you need it, the full HTML5 specs are available on the W3C website.

2 – Add .htaccess support

The file we’re going to create to cache our web page is called a manifest file. Before creating it, we first have to add a directive to the .htaccess file (assuming your server is Apache).

Open the .htaccess file, which is located on your website root, and add the following code:

AddType text/cache-manifest .manifest

This directive makes sure that every .manifest file is served as text/cache-manifest. If the file isn’t, then the whole manifest will have no effect and the page will not be available offline.

3 – Create the manifest file

Now, things are going to be more interesting as we create a manifest file. Create a new file and save it as offline.manifest. Then, paste the following code in it. I’ll explain it later.

CACHE MANIFEST
#This is a comment

CACHE
index.html
style.css
image.jpg
image-med.jpg
image-small.jpg
notre-dame.jpg

Right now, you have a perfectly working manifest file. The way it works is very simple: After the CACHE declaration, you have to list each files you want to make available offline. That’s enough for caching a simple web page like the one from my example, but HTML5 caching has other interesting possibilities.

For example, consider the following manifest file:

CACHE MANIFEST
#This is a comment

CACHE
index.html
style.css

NETWORK:
search.php
login.php

FALLBACK:
/api offline.html

Like in the example manifest file, we have a CACHE declaration that caches index.html and style.css. But we also have the NETWORK declaration, which is used to specify files that shouldn’t be cached, such as a login page.

The last declaration is FALLBACK. This declaration allows you to redirect the user to a particular file (in this example, offline.html) if a resource (/api) isn’t available offline.

4 – Link your manifest file to the html document

Now, both your manifest file and your main html document are ready. The only thing you still have to do is to link the manifest file to the html document.

Doing this is easy: simply add the manifest attribute to the html element as shown below:

<html manifest="/offline.manifest">

5 – Test it

Once done, you’re ready to go. If you visit your index.html file with Firefox 3.5+, you should see a banner like this one:

Other browser I’ve tested (Chrome, Safari, Android and iPhone) do not warn about the file caching, and the file is automatically cached.

Below you’ll find the browser compatibility of this technique: As usual Internet Explorer does not support it.

  • IE: No support
  • Firefox: 3.5+
  • Safari: 4.0+
  • Chrome: 5.0+
  • Opera: 10.6+
  • iPhone: 2.1+
  • Android: 2.0+

10 tips for creating high quality WordPress themes

Respect HTML and CSS standards

This statement may sound pretty obvious, but actually many publicly available themes don’t pass W3C HTML or CSS validation. When building a theme, it is important to respect HTML and CSS standards so your code will be clean and (mostly) cross-browser compatible. A valid HTML/CSS theme is also a proof of quality development.

HTML, XHTML and HTML5 code can be checked on theW3C website. The W3C also have a free tool to check your CSS coding, althought with the rise of CSS3 and its vendor prefixes, it is pretty hard to obtain a 100% valid stylesheet.

Respect WordPress coding standards

Like most other open-source projects, WordPress have its own list of coding standards. This meticulous coding style convention is here to keep harmony among the thousands of themes and plugins availables and maintain a consistent style so the code can become clean and easy to read at a glance.

For example, the coding convention forbids to use PHP shorthand tag:

<? ... ?>
<?=$var?>

Instead, use full PHP tags:

<?php $var; ?>

The complete coding standard guide can be read on WordPress codex. On a personnal note, I really think that WordPress should recommend coding CSS in “blocks” instead of “lines”.

Don’t forget wp_head()

Within the <head> and </head> tags of most WordPress themes, you’ll find a function named wp_head(). This function may look useless to newcommers, but it is extremely important: Many plugins use this function to “hook” code in WordPress header. Without this function within your <head> and </head> tags, lots of plugins will not be able to work.

A similar function named wp_footer(); can be found in the footer.php file of most themes. Don’t forget it as well, it is used by plugins to hook code in your theme footer. For example, analytics.

Be careful when including hacks

Do you know my blog WPRecipes? In case you don’t, it is a place where I share WordPress hacks and code snippets. The site is quite popular among the community and I’m happy that many people seems to enjoy my hacks.

But last year, Gravity Forms developer Carl Hancock let me know that one of my hacks (Named Disable WordPress automatic formatting on posts using a shortcode) was intensively used on themes sold at Themeforest, and caused conflicts with Gravity Forms.

Of course, I felt sorry for the countless hours Carl and his team wasted in support due to the conflict between their plugin, and my hack. This is why hacks may be used on your own theme, or on a client theme, but you should not include hacks in a theme you’re going to distribute, excepted if you know exactly what you’re doing.

Start from something solid

In order to save time, most developers prefer starting coding from an existing theme. For example, I’ve used Cris Coyier’s Blank Theme as the starting point of most of the themes I’ve created in 2010 and 2011.

But don’t start from a finished plugin. I’ve seen themes coded over WooThemes and then re-released. Let me tell you, the code was an absolute nightmare!

If you’re looking for a rock solid basis to create your theme, give a go to Constellation: It is a “blank” HTML5/CSS3 theme, which the current CatsWhoCode theme derives from.

Use localized strings

When coding a WordPress theme or plugin, you have to think about those that doesn’t speak English. Using the PHP language, two very useful functions are available for you to create a translatable theme or plugin:

The first is the function _e(), which prints on screen the desired text, translated into the user language:

_e("Text to translate", "textdomain");

The second is __() wich is basically the same than _e(), but returns the text:

function say_something() {
    return __("Text to translate", "textdomain");
}

By using those functions, you make your work translatable in any language, which is a very great thing for people that blog in another language than English. Don’t forget to read my guide about making multilingual WordPress themes if you want to know more about the topic.

Prefix your php functions

It may looks like a detail at first, but prefixing your php functions is always a good practice. Why? Because most people would name their functions using common names such as display_stuff(). And if a theme developer named one of his functions with the same name that a function from a plugin the end user is using… Boom, the site is broken, and the user is not happy.

A bad example is to name your functions like this:

function display_stuff($stuff){
...
}

Instead, add a prefix such as your initials:

function cwc_display_stuff($stuff){
...
}

It do not require a big effort and it can avoid big problems for the non tech-savvy user.

Test content formating

A blog is used to display content. Then, why so many available themes do not comes with a style for HTML lists or blockquotes? To make sure users will be happy with your theme, you should make sure that all HTML elements looks good.

To do so, you can use a plugin named WP Dummy Content, which allow you to create posts, pages, categories and more so you can check how good you theme looks when it’s full of content.

Another tool to have in your tool box is the WP Lorem Ipsum Post Pack, a XML file that contains categories, sub-categories, pages, sub-pages, 30 test posts, tags, thumbnails via custom fields, and a “Testing the Elements” post so that you can test html elements, such as <h2>, <blockquote>, so you can test your theme in depth. Importing this XML is easy: Login to your dashboard, navigate to Tools → Import, and select the file.

Make sure your theme supports the latests functions

Do you think your theme is ready for public distribution? If yes, you should always make a final checking using the Theme-Check plugin, which is an easy way to test your theme and make sure it’s up to spec with the latest theme review standards.

Theme Check can be installed as any other plugins, and will let you know about any coding mistakes such as the use of a deprecated function.

Release your theme as GPL

With the success of WordPress, people created companies and started to sell “premium” themes. Most of them with released under the terms of the GPL licence, but several theme vendors chose to go with a licence that may, in their opinion, give them a better protection against piracy.

Though, WordPress team stated numerous times that themes have to be GPL compliant.

Although I am not a GPL fanatic, most WordPress users are, and trying to release a theme that is not GPL compliant will make you a pariah, and might even get you a lawsuit. So, don’t do something stupid: Respect WordPress licence, or choose another platform to work on.

Any other useful tip? Feel free to share it in a comment!

Get how many posts are returned by a custom loop

Simply paste the following code snippet anywhere on your theme. It will display how many posts are returned by the custom query.

$feat_loop = new WP_Query( 'showposts=12&category_name=featured' );
echo "Query returned ".$feat_loop->post_count." posts.";

Thanks to WP Lover for the cool tip!

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

Get how many posts are returned by a custom loop

10+ useful tools to simplify CSS3 development

CSS3 Pie


Are you surprised that Internet Explorer 6/8 CSS3 support is almost non existent? I guess most of you aren’t. Unfortunately, some clients may want you to create a website that look like in a modern browser in IE. This is when CSS3 Pie is useful: It allows you to use most of the CSS3 cool features on IE.
→ Visit CSS3 Pie

CSS3 Builder


With this tool, you can design complex CSS3 boxes using an interface looking exactly like the one used for applying Photoshop effects. Definitely a great tool to save lots of time.
→ Visit CSS3 Builder

CSS3 Drop shadow generator


This one is quite similar to CSS3 builder, just use the sliders to visually design your drop shadow. Once done, just copy the CSS code which have been automatically created. Paste it to your css file, and you’re ready to go!
→ Visit CSS3 Drop shadow generator

Cascader


This tool isn’t CSS3 specific, but it is so useful that it would have been a shame not to include it on that list. Cascader lets you input some HTML code and it will detect all inline CSS, remove it from the HTML and add it to a separate stylesheet. A true time saver for those looking for clean HTML.
→ Visit Cascader

Border Radius.com


border-radius is one of the most popular CSS3 properties. Those who remember how boring it was to create boxes with rounded corners using images certainly know why. This tool allow you to quickly create a box and get the appropriate CSS3 code.
→ Visit Border Radius.com

Button Maker


CSS3 allows you to create awesome buttons. This tool, created by Chris Coyier, makes CSS3 button design extremely easy: Just pick colors, adjust radius, and get the code, ready to be pasted into your CSS file.
→ Visit Button Maker

CSS3 Generator


Need help with CSS3 declarations? This very handy generator helps you create declarations for most popular CSS3 properties: @font-face, RGBA, text-shadow, border-radius, and more.
→ Visit CSS3 Generator

Modernizr


Modernizr is a small script that detect support for CSS3 and adds classes to the <html> element which allow you to target specific browser functionality in your stylesheet. For example, if the browser does not support the multiple backgrounds functionality, a no-multiplebgs class will be added to the <html> element. then it will be pretty easy for you to fall back.
→ Visit Modernizr

HTML5 & CSS3 Support


Need to know if Internet Explorer 8 supports the text-shadow property? Just have a look to this very useful chart, which reveals CSS3 support for all major browsers. Definitely a page to have in your bookmarks!
→ Visit HTML5 & CSS3 Support

CSS3 Gradient Generator


As you can guess, this tool is a gradient generator. Just pick your colors using the picker, preview it in the preview area, and grab your ready-to-be-pasted code. It’s easy as that!
→ Visit CSS3 Gradient Generator

CSS3 Please


CSS3 Please is another very helpful site which allow you to copy and paste most common CSS3 declarations. It also has a preview area so you can live test your declarations.
→ Visit CSS3 Please

CSS3 Cheat Sheet


When coding, cheat sheets are very helpful to quickly remember properties and their syntax. Smashing Magazine has created this CSS3 cheat sheet that you can download and print. A preview version in .gif format is also available here.
→ Visit CSS3 Cheat Sheet

Create an adaptable website layout with CSS3 media queries

Getting started

Creating the default layout

The first step of this tutorial is obviously to create a HTML page. I chose to make a simple HTML5 page with only a header image, a title, and some text. Copy the following code and paste it into a file named index.html.

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8">
   	<title>Cats Who Code demo</title>
	<link href="style.css" type="text/css" rel="stylesheet" media="screen">
	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
</head>

<body>
	<div id="container">
		<header class="ma-class-en-css">
			<h1 id ="logo"><a href="#">Cats Who Code</a></h1>
		</header>

		<div id="content">
       		<h2>Paris, France</h2>
        	<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a ligula massa. Donec consequat, risus nec viverra condimentum, elit velit dignissim dui, id congue sapien leo tincidunt est. Mauris consectetur tempus lorem id aliquet. Proin eu faucibus massa. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In magna ligula, ornare sed posuere faucibus, consequat ac lacus. Fusce sodales fermentum nibh, a imperdiet nisi bibendum eget. Donec gravida iaculis sapien eu consectetur. Curabitur id augue augue. Nam mauris urna, suscipit eget faucibus sit amet, mollis vitae felis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris ipsum lectus, imperdiet id aliquam nec, vulputate vitae mauris. Integer gravida, neque eu placerat egestas, urna metus bibendum nisl, quis congue felis velit id diam. Quisque non tortor at turpis facilisis placerat quis sed felis. Ut eget ipsum dolor, id lacinia leo. Vivamus vitae blandit libero. Integer ultricies gravida leo quis lobortis. Morbi ultrices risus vulputate magna dignissim sed ultricies arcu tristique. Sed non facilisis sapien.</p>

			<p>Integer faucibus, augue vitae vulputate sodales, tellus tellus vulputate tortor, in iaculis ipsum orci vitae libero. Vestibulum laoreet accumsan erat vel pretium. Ut turpis elit, ultricies id accumsan non, condimentum feugiat neque. Nam ut erat urna, a porta augue. Donec vel porttitor magna. Cras eget tortor eget ante malesuada sodales sed a leo. Fusce sit amet cursus sem. Nulla aliquet accumsan ante sit amet condimentum. Morbi varius porta sapien nec iaculis. In gravida velit at nulla imperdiet varius.</p>
        </div><!-- #content -->

		<footer>A demo by <a href="http://www.catswhocode.com">CatsWhoCode</a></footer>
	</div><!-- #container -->
</body>
</html>

Once done, we have to add a stylesheet to our index.html page. The following code is the basic styling for the page. Paste it into a file named style.css.

*{
	/* On a production site, use a real reset instead of this! */
	margin:0;
	padding:0;
}            

body{
	background:#f5f5f5;
	font-family:"Lucida Grande", Arial;
	font-size:13px;
	line-height:21px;
	color:#444;
}     

p{
	margin:15px 0;
}              

h2{
	margin-top:20px;
}

#container{
	background:#fff;
	border-left:1px #ddd solid;
	border-right:1px #ddd solid;
	border-bottom:1px #ddd solid;
	width:600px;
	margin:0 auto;
}  

header h1#logo a{
	text-indent:-9999px;
	display:block;
	width:600px;
	height:82px;
	background:url(image-med.jpg) no-repeat 0 0;
}             

#content{
	width:95%;
	margin:0 auto;
}

footer{
	text-align:center;
	width:100%;
	display:block;
	font-size:11px;
}

Right now, if you look to your index.html page through your web browser, you’ll see something like the screenshot below. Nothing spectular, right? Keep reading, we’re going to dive into the interesting part.

Using CSS3 media queries to make our layout fit in all screen resolutions

If you had a look to your index.html page with a screen resolution bigger than 800*600, you might find the layout is really small. So, what about allowing large screens to display a bigger version, while still using the small version for people with lower resolutions?

This is what CSS3 media queries can do for you. Open your style.css file and paste the code below at the end of the file:

@media screen and (min-width:1200px){
	#container{
		width:1100px;
	}  

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

}

Now, have a look at index.html again: The layout is indeed bigger. Horizontally resize the window size… The site switches back to the small layout. How great is that?

As you can see, there’s nothing complicated at all in implementing this technique. @media screen tells the browser this applies only for screens, because we don’t want to resize anything for print. And and (min-width:1200px) specifies that the screen must have a 1200px minimum width. If these requirements are met, then the code within the parenthesis is taken into consideration by the browser, and redefines previous styles.

Now that we created a bigger version for bigger screens, what about a very small version for mobiles? Paste this code into style.css and you’re done.

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

}

Dealing with images

Images always play an important part of a website. So, let’s add an image to our website layout. Re-open index.html and insert the following code just before the first closing </p>

<img src="notre-dame.jpg" alt="Photo by Wlappe">

If you have a look to index.html with a big screen, no problem. But if you resize the window horizontally…ouch.

The solution to that problem is quite simple: As we resize the website layout, we have to resize images as well. The max-width CSS property is here to help.

Insert the following on your style.css file:

img {
	max-width:570px;
	margin:10px 0;
}

A default image size is now defined. Now we can setup sizes for big screens as well as mobile devices:

@media screen and (min-width:1200px){
	img {
		max-width:1000px;
	}
}

@media screen and (max-width:767px){
	img {
    	max-width:305px;
	}
}

Now, resize your browser: Images are resized with the layout!

Limitations

Guess what? Internet Explorer (excepted the newly released IE9) doesn’t know anything about the CSS @media property. Which means that even on a big screen, IE users will see the default layout.

Hope you enjoyed this tutorial. Have a great day!

How to easily disable theme changing

Simply paste the following piece of code in your functions.php file:

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

Once saved, your client will not be able to switch themes anymore.

Thanks to Steve Taylor for this cool recipe!

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

How to easily disable theme changing

How to create an online radio using jQuery and jPlayer

Getting started

Creating the database

First, create a new SQL database. Let’s call it radio. Once done, we have to create a table. We only need 4 fields: An id, the mp3 url, the artist name and the song title. Here is the SQL code to use in order to create the table named songs:

CREATE TABLE `songs` (
  `song_id` int(11) NOT NULL AUTO_INCREMENT,
  `url` varchar(500) NOT NULL,
  `artist` varchar(250) NOT NULL,
  `title` varchar(250) NOT NULL,
  PRIMARY KEY (`song_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

We now have a database and a table to store basic informations about songs we’re going to play on our radio. Now we have to populate the table. Choose some mp3 files and insert the following statement into your database:

INSERT INTO `songs` (`song_id`, `url`, `artist`, `title`) VALUES ('', 'http://mysongs.com/songurl.mp3', 'Artist name', 'Song name');
INSERT INTO `songs` (`song_id`, `url`, `artist`, `title`) VALUES ('', 'http://mysongs.com/anothersongurl.mp3', 'Another artist', 'Another song');
INSERT INTO `songs` (`song_id`, `url`, `artist`, `title`) VALUES ('', 'http://mysongs.com/onemoresongurl.mp3', 'One more artist', 'One more song');

Right now, the database is ready.

Creating the HTML

Of course, we have to create a HTML page. First, grab your copy of jPlayer, the jQuery plugin we’re going to use to create the online radio. Unzip the file, then upload the js/ and skin/ to your server.

Then, create a file named demo.html on your server and insert the following code into it:

<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' lang='en' xml:lang='en'>
<head>
	<title>Online radio using jQuery</title>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

	<link href="skin/jplayer.blue.monday.css" rel="stylesheet" type="text/css" />

	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
	<script type="text/javascript" src="js/jquery.jplayer.min.js"></script>
</head>

<body>
	<div id="jquery_jplayer_1" class="jp-jplayer"></div>
		<div class="jp-audio">
			<div class="jp-type-single">
		    	<div id="jp_interface_1" class="jp-interface">
					<ul class="jp-controls">
						<li><a href="#" class="jp-play" tabindex="1">play</a></li>
						<li><a href="#" class="jp-pause" tabindex="1">pause</a></li>
						<li><a href="#" class="jp-stop" tabindex="1">stop</a></li>
						<li><a href="#" class="jp-mute" tabindex="1">mute</a></li>
						<li><a href="#" class="jp-unmute" tabindex="1">unmute</a></li>
					</ul>

					<div class="jp-progress">
						<div class="jp-seek-bar">
							<div class="jp-play-bar"></div>
						</div>
					</div>

					<div class="jp-volume-bar">
						<div class="jp-volume-bar-value"></div>
					</div>

					<div class="jp-current-time"></div>
					<div class="jp-duration"></div>
				</div>

				<div id="jp_playlist_1" class="jp-playlist">
					<ul>
						<li><strong id="artist">Artist</strong> - <span id="songname">Song name</span></li>
					</ul>
				</div>
			</div>
		</div>
	</div>
</body>

</html>

This code has been taken from jPlayer’s demos. It is a simple html code that insert the necessary JavaScript files (jQuery + the jPlayer plugin) as well as the CSS and html used to display the music player. Right now, the player do no even display correctly: We still have to use some jQuery to animate it. We’ll see that in a minute.

Getting files from the database

Now, we have to create a PHP file that will get a random song from the database, and display the file url as well as the artist and song name so we can grab it using Ajax. First, get your copy of ezSQL, that I chose to use to manage my database queries. (Full ezSQl tutorial available here) Unzip the files and upload ez_sql_core.php and ez_sql_mysql.php to the server.

Once done, create a file named getsong.php on the server. Paste the following code in it:

<?php

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){ 

	include_once "ez_sql_core.php";
	include_once "ez_sql_mysql.php";
	$db = new ezSQL_mysql('db_user','db_password','db_name','db_host'); 

	$song = $db->get_row("SELECT * FROM songs ORDER BY RAND() LIMIT 1");

	$artist = $song->artist;
	$songname = $song->title;
	$url = $song->url;
	$separator = '|';
	echo $url.$separator.$artist.$separator.$songname;
} 

?>

Nothing complicated: I’ve inclued the ezSQL files needed, created a connection to the database, then requested one row from the songs table. The 3 values (File url, artist, and song name) are displayed on screen, separated by a pipe.

The conditionnal statement is used to detect Ajax requests and prevent people from being able to display songs url by simply typing http://www.yousite.com/getsong.php on their browser adress bar.

Making it work

Alright, we’re almost done. What we need now is to use some jQuery to request a song using Ajax and our getsong.php file. Then, we’ll use jPlayer to play it.

Open your demo.html and paste the following after line 10:

<script type="text/javascript">
//<![CDATA[

$(document).ready(function(){
	$("#jquery_jplayer_1").jPlayer({
		ready: function () {
			var data = $.ajax({
			  url: "getsong.php",
			  async: false
			 }).responseText;

		    var string = data.split('|');
			$(this).jPlayer("setMedia", {
				mp3: string[0]
			}).jPlayer("play");

			$('#artist').html(string[1]);
			$('#songname').html(string[2]);
		},
		ended: function (event) {
			var data = $.ajax({
			  url: "getsong.php",
			  async: false
			 }).responseText;

		    var string = data.split('|');
			$(this).jPlayer("setMedia", {
				mp3: string[0]
			}).jPlayer("play");

			$('#artist').html(string[1]);
			$('#songname').html(string[2]);
	    },
		swfPath: "js",
		supplied: "mp3"
	});
});
//]]>
</script>

Now, if you save the file and point your browser to http://www.yousite.com/demo.html, your radio should work: It gets a song from the database and play it. When the song’s over, another one is automatically selected.

There’s probably better ways to write this code (It use a lot of redondant code, which is always a bad practise) so don’t hesitate to write a comment if you have a better version to suggest.

How to enhance the script

While we have a working radio, it is very basic and can be enhanced: For example, we should exclude song already played (using songs id stored in the database) or even better, create playlists. I haven’t worked on it yet, but if you are interested let me know in a comment and I might write a tutorial about it.

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

How to create an online radio using jQuery and jPlayer

Add custom links to WordPress admin bar

To add a custom link to WordPress admin bar, simply paste the following code into your functions.php file. Modify the code as needed to fit your needs.

function mytheme_admin_bar_render() {
	global $wp_admin_bar;
	$wp_admin_bar->add_menu( array(
		'parent' => 'new-content', // use 'false' for a root menu, or pass the ID of the parent menu
		'id' => 'new_media', // link ID, defaults to a sanitized title value
		'title' => __('Media'), // link title
		'href' => admin_url( 'media-new.php'), // name of file
		'meta' => false // array of any of the following options: array( 'html' => '', 'class' => '', 'onclick' => '', target => '', title => '' );
	));
}
add_action( 'wp_before_admin_bar_render', 'mytheme_admin_bar_render' );

Thanks to Jeff Starr for the cool tip!

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

Add custom links to WordPress admin bar

How to show an urgent message in the WordPress admin area

The following is a snippet of my custom function that shows a message to the user. This be used from anywhere in your theme or plugin if you wanted to give the user a standard message. e.g. “Settings successfully updated” or something similar.

/**
 * Generic function to show a message to the user using WP's
 * standard CSS classes to make use of the already-defined
 * message colour scheme.
 *
 * @param $message The message you want to tell the user.
 * @param $errormsg If true, the message is an error, so use
 * the red message style. If false, the message is a status
  * message, so use the yellow information message style.
 */
function showMessage($message, $errormsg = false)
{
	if ($errormsg) {
		echo '<div id="message" class="error">';
	}
	else {
		echo '<div id="message" class="updated fade">';
	}

	echo "<p><strong>$message</strong></p></div>";
}    

Now we just add a hook to the admin notices function to show our custom message.

/**
 * Just show our message (with possible checking if we only want
 * to show message to certain users.
 */
function showAdminMessages()
{
    // Shows as an error message. You could add a link to the right page if you wanted.
    showMessage("You need to upgrade your database as soon as possible...", true);

    // Only show to admins
    if (user_can('manage_options') {
       showMessage("Hello admins!");
    }
}

/**
  * Call showAdminMessages() when showing other admin
  * messages. The message only gets shown in the admin
  * area, but not on the frontend of your WordPress site.
  */
add_action('admin_notices', 'showAdminMessages');

And that’s all there is to it!

Thanks to Dan Harrison of WordPress Doctors for the tip!

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

How to show an urgent message in the WordPress admin area

Top 10 CSS 3 forms tutorials

HTML5 & CSS3 form


HTML5 introduced useful new form elements as such as sliders, numeric spinners and date pickers. This tutorial will show you how to create a form with HTML5, and make it look really cool with CSS3. A great way to get started in both CSS3 and HTML5.
» View tutorial

CSS3 form without images and JavaScript


This tutorial is in French, but the result looks so good that I simply shouldn’t include it on that list. For those who can’t understand French, just get the source code and have fun with it.
» View tutorial

Stylish Contact Form with HTML5 & CSS3


I really love what British web developer Chris Spooner creates. This time, he’s back with a quality tutorial about creating a form and using CSS3 to style it. The result is, as you can see above, really cool.
» View tutorial

Beautiful CSS3 Search Form


Most search forms (Including the one I use on this site!) looks boring. Using a little CSS3, you can turn the old and boring form into something definitely modern and cool. A must read tutorial.
» View tutorial

Prettier Web Form with CSS 3


This pretty simple tutorial will show you how you can create a form using some basic CSS3 properties, such as box-shadow.
» View tutorial

Slick CSS3 Login Form


Once again, a simple tutorial to create a simple form using CSS3 but absolutely no images.
» View tutorial

Glowform: Amazing CSS3 form


Wow! This form looks really great, isn’t it? This form do not use any images, only CSS3. I urge you to read this tutorial and the form source code, because you’ll learn lots of great techniques about creating killer forms without using images.
» View tutorial

Clean and Stylish CSS3 Form


This form is simple, clean and stylish. Nothing fancy but techniques you’ll may use on most websites you’ll make.
» View tutorial

Signup form with CSS3 and jQuery


jQuery is definitely a great tool to make forms more usable. This tutorial will show you how to create a good looking form using CSS3, and how to make it more user-friendly with some jQuery.
» View tutorial

jQuery & CSS3 Drop-down menu with integrated forms


At last but not least, here is a tutorial about how to create a CSS3/jQuery dropdown menu with integrated forms. No doubt, your clients will love it!
» View tutorial

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

Top 10 CSS 3 forms tutorials

10 super useful PHP snippets

Super simple page caching

When your project isn’t based on a CMS or framework, it can be a good idea to implement a simple caching system on your pages. The following code snippet is very simple, but works well for small websites.

<?php
    // define the path and name of cached file
    $cachefile = 'cached-files/'.date('M-d-Y').'.php';
    // define how long we want to keep the file in seconds. I set mine to 5 hours.
    $cachetime = 18000;
    // Check if the cached file is still fresh. If it is, serve it up and exit.
    if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    include($cachefile);
        exit;
    }
    // if there is either no file OR the file to too old, render the page and capture the HTML.
    ob_start();
?>
    <html>
        output all your html here.
    </html>
<?php
    // We're done! Save the cached content to a file
    $fp = fopen($cachefile, 'w');
    fwrite($fp, ob_get_contents());
    fclose($fp);
    // finally send browser output
    ob_end_flush();
?>

» Credit: Wes Bos

Calculate distances in PHP

Here is a very handy function, which calculate the distance from a point A to a point B, using latitudes and longitudes. The function can return the distance in miles, kilometers, or nautical miles.

function distance($lat1, $lon1, $lat2, $lon2, $unit) { 

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

Usage:

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k")." kilometers";

» Credits: PHP Snippets.info

Convert seconds to time (years, months, days, hours…)

This useful function will convert a time in seconds to a time in years, months, weeks, days, and so on.

function Sec2Time($time){
  if(is_numeric($time)){
    $value = array(
      "years" => 0, "days" => 0, "hours" => 0,
      "minutes" => 0, "seconds" => 0,
    );
    if($time >= 31556926){
      $value["years"] = floor($time/31556926);
      $time = ($time%31556926);
    }
    if($time >= 86400){
      $value["days"] = floor($time/86400);
      $time = ($time%86400);
    }
    if($time >= 3600){
      $value["hours"] = floor($time/3600);
      $time = ($time%3600);
    }
    if($time >= 60){
      $value["minutes"] = floor($time/60);
      $time = ($time%60);
    }
    $value["seconds"] = floor($time);
    return (array) $value;
  }else{
    return (bool) FALSE;
  }
}

» Credits

Force file download

Some files, such as mp3, are generally played throught the client browser. If you prefer forcing download of such files, this is not a problem: The following code snippet will do that job properly.

function downloadFile($file){
        $file_name = $file;
        $mime = 'application/force-download';
	header('Pragma: public'); 	// required
	header('Expires: 0');		// no cache
	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	header('Cache-Control: private',false);
	header('Content-Type: '.$mime);
	header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
	header('Content-Transfer-Encoding: binary');
	header('Connection: close');
	readfile($file_name);		// push it out
	exit();
}

» Credit: Alessio Delmonti

Get current weather using Google API

Want to know today’s weather? This snippet will let you know, in only 3 lines of code. The only thing you have to do is to replace ADDRESS by the desired adress, on line 1.

$xml = simplexml_load_file('http://www.google.com/ig/api?weather=ADDRESS');
  $information = $xml->xpath("/xml_api_reply/weather/current_conditions/condition");
  echo $information[0]->attributes();

» Credit: Ortanotes

Basic PHP whois

Whois services are extremely useful to get basic information about a domain name: owner, creation date, registrar, etc. Using PHP and the whois unix command, it is extremely easy to create a basic whois PHP function. Please note that the whois unix command must be installed on your server for this code to work.

$domains = array('home.pl', 'w3c.org');

function creation_date($domain) {
    $lines = explode("\n", `whois $domain`);
    foreach($lines as $line) {
        if(strpos(strtolower($line), 'created') !== false) {
            return $line;
        }
    }

    return false;
}

foreach($domains as $d) {
    echo creation_date($d) . "\n";
}

» Credits: Snipplr

Get latitude and longitude from an adress

With the popularity of the Google Maps API, developers often needs to get the latitude and longitude of a particular place. This very useful function takes an adress as a parameter, and will return an array of data containing both latitude and longitude.

function getLatLong($address){
	if (!is_string($address))die("All Addresses must be passed as a string");
	$_url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($address));
	$_result = false;
	if($_result = file_get_contents($_url)) {
		if(strpos($_result,'errortips') > 1 || strpos($_result,'Did you mean:') !== false) return false;
		preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
		$_coords['lat'] = $_match[1];
		$_coords['long'] = $_match[2];
	}
	return $_coords;
}

» Credits: Snipplr

Get domain favicon using PHP and Google

These days, many websites or webapps are using favicons from other websites. Displaying a favicon on your own site is pretty easy using Google and some PHP.

function get_favicon($url){
  $url = str_replace("http://",'',$url);
  return "http://www.google.com/s2/favicons?domain=".$url;
}

» Credits: Snipplr

Calculate Paypal fees

Ah, Paypal fees. Every person who ever used the popular online payment service had to pay their fees. So what about a PHP function to easily calculate the fee for a specific amount?

function paypalFees($sub_total, $round_fee) {

	// Set Fee Rate Variables
	$fee_percent = '3.4'; // Paypal's percentage rate per transaction (3.4% in UK)
	$fee_cash    = '0.20'; // Paypal's set cash amount per transaction (£0.20 in UK)

	// Calculate Fees
	$paypal_fee = ((($sub_total / 100) * $fee_percent) + $fee_cash);

	if ($round_fee == true) {
		$paypal_fee = ceil($paypal_fee);
	}

	// Calculate Grand Total
	$grand_total = ($sub_total + $paypal_fee);

	// Tidy Up Numbers
	$sub_total   = number_format($sub_total, 2, '.', ',');
	$paypal_fee  = number_format($paypal_fee, 2, '.', ',');
	$grand_total = number_format($grand_total, 2, '.', ',');

	// Return Array
	return array('grand_total'=>$grand_total, 'paypal_fee'=>$paypal_fee, 'sub_total'=>$sub_total);
}

» Credits: Snipplr

(Last snippet have been removed due to an error, sorry)

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

10 super useful PHP snippets

How to manually update your WordPress login

To achieve this recipe, login to your PhpMyAdmin, select your WordPress database and click on the “SQL” button to open the SQL query window.

Then, paste the following code in the window textarea. Don’t forget to modify the password and username before executing it. Also, make sure you have a backup of your database before executing any SQL queries.

UPDATE wp_users SET user_login = 'New login' WHERE user_login = 'Admin';

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

How to manually update your WordPress login